A sorted array that has been rotated, such as [15, 18, 22, 3, 7, 9, 11], is not sorted any more, yet binary search still works with a twist: whichever half you split it into, at least one half is properly sorted, and you can check whether the target lies inside that sorted half.
Picture the numbers printed round a dial. A list of distinct integers was put in ascending order and then the dial was turned: some unknown number of values were lifted off the front and placed, in order, on the back. Given the turned list nums and an integer target, return the index where target sits, or -1 if it is not on the dial.
Examples
Input: nums = [15, 18, 22, 3, 7, 9, 11], target = 7
Output: 4
Input: nums = [15, 18, 22, 3, 7, 9, 11], target = 10
Output: -1
Input: nums = [5], target = 2
Output: -1
Constraints
numswas sorted ascending and then rotated at some pivot; the rotation may be by zero positions (already sorted).- Aim for O(log n) time.
Goals
- Recognise that at least one half of a rotated sorted array is still sorted
- Decide which half is sorted by comparing nums[lo] with nums[mid]
- Use a range check on the sorted half to decide where to continue searching