What is Search in a Rotated Array
A sorted array of distinct values was rotated, so it looks like two increasing runs. Return the index of target, or -1. One half of the current window is still sorted. Keep the half that could contain the target.
4 5 6 7 0 1 2 target 0 4
Approach
The array was sorted, then rotated, so one of the two halves around the middle is still sorted. Compare the target with that sorted half and throw the other half away.
Values are distinct, so a match at mid is the only answer. If the window empties, the target is missing and the answer is -1.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log n) | One comparison chooses a half. |
| Memory | O(1) | Only lo, hi, and mid are stored. |
Implementation
def search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[lo] <= a[mid]:
if a[lo] <= target < a[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
if a[mid] < target <= a[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1