153. Find Minimum in Rotated Sorted Array
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
- [4,5,6,7,0,1,2] if it was rotated 4 times.
- [0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Example 2:
Example 3:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- All the integers of nums are unique.
- nums is sorted and rotated between 1 and n times.
Constraints:
Notes
Intuition
In a rotated sorted array, the minimum element is the pivot point where the rotation occurred. It's the only element where both neighbors are larger (or it's at a boundary).
Implementation
Use binary search. The stop condition is when the element before and after mid are both greater (or mid is at a boundary). To decide which half to search, compare nums[mid] with nums[r]—if mid is larger, the minimum is in the right half; otherwise, it's in the left half.
Edge-cases
Boundary checks are essential. When mid is 0 or n-1, we can't compare with neighbors, so include these cases in the stop condition to avoid index out of bounds.
- Time: O(log n) — binary search halves the range each iteration
- Space: O(1) — only tracking pointers