Find Minimum in Rotated Sorted Array
A sorted array was rotated, e.g. [3, 4, 5, 1, 2]. Compare the middle with the rightmost element: if nums[mid] > nums[hi], the drop (and the minimum) is to the right of mid; otherwise the minimum is at mid or to its left.
Traced input: nums = [4, 5, 6, 7, 0, 1, 2] → 0. Original problem: neetcode.io/problems/find-minimum-in-rotated-sorted-array
Complexity
BestO(log n)
AverageO(log n)
WorstO(log n)
SpaceO(1)
Values are distinct, so every comparison discards half.
Key idea
- The minimum is the only element smaller than its predecessor: the rotation point.
nums[mid] > nums[hi]means the rotation point is in(mid, hi].- Otherwise
[mid, hi]is sorted, so the minimum is in[lo, mid]. - Stop when
lo == hi.
Common mistakes
- Comparing with
nums[lo]instead ofnums[hi]breaks on arrays that aren't rotated. - Using
hi = mid - 1in the else branch can skip the minimum.
Solution
Java
int findMin(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > nums[hi]) {
lo = mid + 1;
} else {
hi = mid;
}
}
return nums[lo];
}Python
def findMin(nums: List[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid
return nums[lo]C++
int findMin(vector<int>& nums) {
int lo = 0, hi = (int)nums.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > nums[hi]) {
lo = mid + 1;
} else {
hi = mid;
}
}
return nums[lo];
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
Not rotatedhi keeps moving left to index 0. | nums = [11, 13, 15, 17] | 11 |
Rotated by onenums[0] > nums[1], so lo moves to 1. | nums = [2, 1] | 1 |
| Single element Already lo == hi. | nums = [1] | 1 |
| Minimum at the end The drop is at the last position. | nums = [2, 3, 4, 5, 1] | 1 |