Find Minimum in Rotated Sorted Array – Solution & Complexity
Solution Walkthrough
Step 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.
- A rotated ascending array is two sorted runs, e.g.
Step 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.
Step 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.
- Compare
Step 4: Logarithmic solution
- Keep halving the search window based on the comparison above.
- No
mid + 1on the right side, becausemiditself may be the minimum.
Step 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 > 2left = 44 6 5 1 <= 2right = 54 5 4 0 <= 1right = 44 4 — loop ends answer nums[4] = 0Step 6: Final solution and complexity
Binary search finds the pivot in
O(log n)time andO(1)extra space.