Find Minimum in Rotated Sorted Array – Solution & Complexity
Solution Walkthrough
1. Read the rotated structure
- A rotated ascending array is two sorted runs, e.g.
[4,5,6,7]then[0,1,2]. - The minimum value is exactly the first element of the second run (the pivot).
- If the array is not rotated, the pivot is index
0.
2. Brute-force scan
- The simplest answer is to scan every element and track the smallest.
- This is
O(n)and ignores the sorted structure, but it is a good correctness baseline.
3. Binary search on the halves
- Compare
nums[mid]withnums[right]. - If
nums[mid] > nums[right], the pivot is to the right, so moveleft = mid + 1. - Otherwise the pivot is at
midor to its left, so moveright = mid. - The loop ends when
left == right, pointing at the minimum.
4. Logarithmic solution
- Keep halving the search window based on the comparison above.
- No
mid + 1on the right side, becausemiditself may be the minimum.
5. Dry run
Trace nums = [4, 5, 6, 7, 0, 1, 2].
| left | right | mid | nums[mid] vs nums[right] | action |
|---|---|---|---|---|
| 0 | 6 | 3 | 7 > 2 | left = 4 |
| 4 | 6 | 5 | 1 <= 2 | right = 5 |
| 4 | 5 | 4 | 0 <= 1 | right = 4 |
| 4 | 4 | — | loop ends | answer nums[4] = 0 |
6. Final solution and complexity
Binary search finds the pivot in O(log n) time and O(1) extra space.