CodeArchon

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
0
lo
5
1
6
2
7
3
0
4
1
5
2
6
hi
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.

1def rotated_target_hunt(nums: list[int], target: int) -> int:
2 lo, hi = 0, len(nums) - 1
3 while lo <= hi:
4 mid = (lo + hi) // 2
5 if nums[mid] == target:
6 return mid
7 if nums[lo] <= nums[mid]:
8 if nums[lo] <= target < nums[mid]:
9 hi = mid - 1
10 else:
11 lo = mid + 1
12 else:
13 if nums[mid] < target <= nums[hi]:
14 lo = mid + 1
15 else:
16 hi = mid - 1
17 return -1
Variables
lo=0
hi=6
target=0

How to think about it

  1. Rotation leaves exactly one half of (lo..mid) and (mid..hi) sorted.
  2. nums[lo] ≤ nums[mid] ⇒ left half sorted. Else right half sorted.
  3. Check if target lies inside the sorted half (half-open interval).
  4. 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 14
{"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