Search in Rotated Sorted Array
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
- 1 <= nums.length <= 5000
- -10^4 <= nums[i], target <= 10^4
- All values of nums are unique
nums = [4,5,6,7,0,1,2], target = 04nums = [4,5,6,7,0,1,2], target = 3-1Searching for a target in a rotated array is tricky because the "sorted order" is broken by a rotation point.
You could just scan every element (O(N)). But for large inputs, we want the logarithmic efficiency of Binary Search. The problem is: how do we binary search if the array isn't perfectly sorted?
Discover: No matter where you pick a midpoint in a rotated sorted array, at least one half is always perfectly sorted.
left = 0
right = length - 1
WHILE left <= right:
mid = left + (right - left) / 2
IF nums[mid] == target: RETURN mid
// Identify which half is "Clean" (Sorted)
IF nums[left] <= nums[mid]:
// Left half is clean
IF target >= nums[left] AND target < nums[mid]:
right = mid - 1 // Target is in the clean left half
ELSE:
left = mid + 1 // Target is in the messy right half
ELSE:
// Right half is clean
IF target > nums[mid] AND target <= nums[right]:
left = mid + 1 // Target is in the clean right half
ELSE:
right = mid - 1 // Target is in the messy left half
RETURN -1Search in Rotated Array is the ultimate test of "Decision Logic." Binary Search works not because the data is perfectly ordered, but because we can definitively eliminate half the search space based on a single condition. By identifying the "clean" half of the rotation, we maintain O(log N) speed even in a fragmented landscape.
Search in Rotated Array
One half of the array is always sorted. Identify the sorted half, then check if the target lies within its range.