Search in a Rotated Sorted Array: The Binary Search Twist Interviewers Love

A sorted array rotated at an unknown pivot, like [4,5,6,7,0,1,2], still lets you search in O(log n). The trick is that at every midpoint, at least one half is still sorted.

The core idea

Compute mid. If nums[lo] <= nums[mid], the left half is sorted: check whether the target lies between nums[lo] and nums[mid], and move accordingly. Otherwise the right half is sorted, so do the same check on nums[mid]..nums[hi].

Variants you should know

Edge cases

Arrays of length one or two, no rotation at all, and a target equal to the pivot value. Walk through [1] and [3,1] before you say you are done.

Presenting it

State the invariant ("one half is always sorted") first, then code. Interviewers grade the reasoning as much as the result. For practicing these explanations against a timer, I use real-time interview help.

Disclosure: I work on Linkjob AI.