A sorted (ascending) array of distinct values has been rotated at an unknown pivot.
Return the index of target, or -1 if absent, in O(log n).
searchRotated(nums, target)
Input format: nums | target.
[4, 5, 6, 7, 0, 1, 2], target=0 // → 4
[4, 5, 6, 7, 0, 1, 2], target=3 // → -1
[1], target=1 // → 0
A rotated array seems to break binary search — comparing the target to the middle doesn't tell you which half to search the usual way. But the array is exactly two contiguous sorted runs (the tail of the original wrapped to the front). That structure is what makes binary search still possible.
At any step, look at [lo, mid]. Either this left portion is properly sorted, or the rotation break is inside it, forcing [mid, hi] to be sorted instead. One comparison tells you which: if nums[lo] <= nums[mid], the left portion is sorted (a rotation break inside it would force nums[lo] > nums[mid]). Otherwise, the right portion is sorted.
Once you know which half is sorted, check whether the target could fall within its value range. If so, search there — the target definitely isn't in the other, unsorted-looking half. If not, search the other half instead.
Either way, one comparison discards half the current range, just like standard binary search — the only extra step is figuring out which half is safe to reason about first.
A linear scan takes time proportional to the array's length. This approach preserves binary search's core guarantee — eliminating half the range each comparison — since even though the whole array isn't sorted, at least one half always is, and that's enough for a safe halving decision every step.
def search_rotated(nums, target):
lo = 0
hi = len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]:
# left half sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
# right half sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.