A sorted array of distinct values was rotated at an unknown index. Given the rotated array and a target, return the target's index or -1, in O(log n).
Before you code
The array has one drop. Split any range in two and one half has no drop, so it is sorted, and a range check on that half is reliable.
Hints
- If
a[lo] <= a[mid], the left half is sorted; otherwise the right half is. - If the target lies within the sorted half's end values, search there; otherwise search the other half.
- Use a closed range consistently:
while lo <= hi,hi = mid - 1,lo = mid + 1.
Production & complexity notes
When solving Search in rotated sorted array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rotated and two-dimensional data to reinforce the underlying pattern.
What it practices
Binary search on partly sorted data, from Rotated and two-dimensional data.