← Deloitte bank

Deloitte · Question 28 · Binary Search

Search in Rotated Sorted Array

Binary SearchJavacode⏱ O(logn)💾 O(1)
Service-based

Problem

Find the target in an array rotated at an unknown pivot.

Approach

Use modified binary search: detect the sorted half each step.

Time O(logn)Space O(1)

How it works

  1. 1Find the sorted half via nums[l] vs nums[mid].
  2. 2Narrow into the half that can hold the target.

Sample input / output

Input:
nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output:
4

Constraints

Distinct values; 1 <= n <= 5000.

Solution — read it, then walk it

Time O(logn)Space O(1)Loops 1Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intsearch(int[] nums, inttarget)DEFINE l = 0, r =nums.length - 1while (l <= r)DEFINE mid = l + (r - l) /2if (nums[mid] ==target) return midif (nums[l] <=nums[mid])if (target >= nums[l]&& target < nums[mid])r = mid - 1ELSE} elseRETURN -1DEFINE static voidmain(String[] args)System.out.println(search(newint[]{4, 5, 6, 7, 0, 1, 2},0))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/15

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits