mediumBinary SearchAmazonGoogleMicrosoft
Rotated Target Hunt
A previously sorted catalog was rotated unknown times. Locate a target entry in O(log n).
Given a rotated sorted array of distinct integers and a `target`, return the index of target or −1.
Choose approach
4
0lo
5
16
27
30
41
52
6hi
1/4
Narrationstep 1 of 4
Pivoted sorted array. At each probe, one half (lo..mid or mid..hi) is still properly sorted. Decide where the target can live.
Variables
lo=0
hi=6
target=0
How to think about it
- Rotation leaves exactly one half of (lo..mid) and (mid..hi) sorted.
- nums[lo] ≤ nums[mid] ⇒ left half sorted. Else right half sorted.
- Check if target lies inside the sorted half (half-open interval).
- If yes, recurse there; if no, go to the other half.
Edge cases to catch in interview
- No rotation — behaves like plain binary search.
- Target equal to a boundary — half-open check matters.
- Rotation at the very end (n-1 rotations) — left half always sorted.
Examples
Example 1
4{"nums":[4,5,6,7,0,1,2],"target":0,"values":[4,5,6,7,0,1,2]}
Example 2
-1{"nums":[4,5,6,7,0,1,2],"target":3,"values":[4,5,6,7,0,1,2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed