Full answer
Problem
A sorted list of distinct values was rotated, for example [0, 1, 2, 4, 5, 6, 7] became [4, 5, 6, 7, 0, 1, 2]. Given the rotated list and a target, return its index or -1 in O(log n).
Example: [4, 5, 6, 7, 0, 1, 2], target 0 gives 4; target 3 gives -1.
Constraints: 0 <= len(nums) <= 5000, distinct values.
Brute force
Linear scan: O(n).
Two-step alternative: binary search for the rotation point (the minimum), then do a normal binary search in the correct part. Also O(log n), with two loops.
Optimal approach
While lo <= hi:
mid = (lo + hi) // 2; returnmidif it matches.- If
nums[lo] <= nums[mid], the left half[lo, mid]is sorted:- If
nums[lo] <= target < nums[mid], search left (hi = mid - 1); else search right.
- If
- Otherwise the right half
[mid, hi]is sorted:- If
nums[mid] < target <= nums[hi], search right (lo = mid + 1); else search left.
- If
Why it works
A rotation creates at most one "drop" in the list. The drop is either in the left half or the right half, not both, so one half is sorted. For a sorted half, a range check tells you exactly whether the target can be there. If not, it can only be in the other half. The search range halves each step, preserving the invariant that the target, if present, is in [lo, hi].
<= in nums[lo] <= nums[mid] matters when lo == mid (a range of one or two elements).
Complexity
O(log n) time, O(1) space.
Code
def search_rotated(nums, target):
"""Search a rotated sorted list of distinct values. O(log n)."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert search_rotated([1], 0) == -1
assert search_rotated([1], 1) == 0
assert search_rotated([], 1) == -1
assert search_rotated([3, 1], 1) == 1
base = list(range(10))
for r in range(10): # every rotation, every value
rotated = base[r:] + base[:r]
for x in base:
assert search_rotated(rotated, x) == rotated.index(x)
print("all tests passed")Save as a29_rotated_search.py and run python3 a29_rotated_search.py. It prints all tests passed (Python 3.13.5).
Edge cases
Not rotated at all. Rotated by one. Two elements ([3, 1]). One element. Empty list. The test runs every rotation of 0 to 9 and every target. With duplicates allowed ([1, 1, 1, 0, 1]), you cannot always tell which half is sorted; the fix is to shrink lo and hi when nums[lo] == nums[mid] == nums[hi], which degrades the worst case to O(n).
Pattern
Binary search with a "which half is ordered" decision. Related: find the minimum of a rotated list and find a peak element, both of which binary search on a local property rather than a target value.
def search_rotated(nums, target):
"""Search a rotated sorted list of distinct values. O(log n)."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 0) == 4
assert search_rotated([4, 5, 6, 7, 0, 1, 2], 3) == -1
assert search_rotated([1], 0) == -1
assert search_rotated([1], 1) == 0
assert search_rotated([], 1) == -1
assert search_rotated([3, 1], 1) == 1
base = list(range(10))
for r in range(10): # every rotation, every value
rotated = base[r:] + base[:r]
for x in base:
assert search_rotated(rotated, x) == rotated.index(x)
print("all tests passed")One-loop binary search choosing the sorted half; the tests check every rotation of a 10-element list.
Complexity
Time: O(log n). Space: O(1). With duplicates allowed, the worst case becomes O(n).
By level
Fresher: Explains why one half is sorted and implements the search, testing the example and a two-element list. Should test a list that is not rotated.
Mid: Handles boundary conditions carefully, gives the two-step alternative and explains the duplicate case. Tests two-element lists and targets at the rotation point.
Senior: Proves the invariant, analyses the duplicate worst case and connects the technique to other local-property binary searches. Can explain why the same idea finds the minimum of a rotated list.
Key points
- At least one half around mid is sorted
- Use nums[lo] <= nums[mid] to detect a sorted left half
- Range-check the target in the sorted half
- Otherwise search the other half
- Duplicates break the guarantee and can force O(n)
Common mistakes
- Using < instead of <= and failing on two-element ranges
- Range checks with wrong inclusive bounds
- Finding the pivot with a linear scan
- Claiming O(log n) when duplicates are allowed
Follow-ups
- How would you find the rotation point itself?
- What changes with duplicates?
- How would you find the minimum element?
Tips
- Draw the rotated list as two rising slopes
- Explain the sorted-half test first
- Test all small rotations
Evaluation rubric
- Correct single-pass binary search
- Correct inclusive range checks
- Handles small arrays
- Discusses duplicates