Find Minimum in Rotated Sorted Array
Find Minimum in Rotated Sorted Array is a medium binary search problem solved with the rotated array pattern.
The best approach, optimal (binary search against nums[hi]), runs in O(log n) time and O(1) space.
Below are 2 approaches in Java, from linear scan up.
Problem
A sorted array of distinct values was rotated at an unknown pivot. Return its minimum in O(log n) time.
Examples
Example 1
- Input
nums = [4, 5, 6, 1, 2, 3]- Output
1
Example 2
- Input
nums = [2, 4, 8]- Output
2
Constraints
1 <= nums.length <= 5000, distinct values.- O(log n).
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Linear scan | O(n) | O(1) |
| Optimal (binary search against nums[hi]) | O(log n) | O(1) |
1Linear scan
O(n)O(1)Return the smallest element.
- Track the minimum.
class Solution {
public int findMin(int[] nums) {
int min = nums[0];
for (int x : nums) min = Math.min(min, x);
return min;
}
}2Optimal (binary search against nums[hi])
O(log n)O(1)If nums[mid] > nums[hi], the drop, and so the minimum, is to the right of mid. Otherwise the part mid..hi is sorted, so the minimum is at mid or to its left.
- While lo < hi: if nums[mid] > nums[hi] lo = mid + 1, else hi = mid.
- Return nums[lo].
class Solution {
public int findMin(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (nums[mid] > nums[hi]) lo = mid + 1;
else hi = mid;
}
return nums[lo];
}
}Edge cases to test
- Not rotated
- Two elements
Hints
Hint 1
Compare nums[mid] with nums[hi], not nums[lo].
FAQ
What is the best time complexity for Find Minimum in Rotated Sorted Array?
Optimal (binary search against nums[hi]) runs in O(log n) time and O(1) extra space.
Which pattern does Find Minimum in Rotated Sorted Array use?
It is a binary search problem that uses the rotated array pattern. Other problems with the same pattern: Find How Many Times Array is Rotated, Find Minimum in Rotated Sorted Array II, Search in Rotated Sorted Array.
Is there a brute force solution for Find Minimum in Rotated Sorted Array?
Yes. Linear scan takes O(n) time and O(1) space. Return the smallest element.
Which edge cases should I test for Find Minimum in Rotated Sorted Array?
Not rotated; Two elements.