Find Minimum in Rotated Sorted Array
Medium · Binary search
Jump to codeA nonempty array of distinct integers was sorted ascending, then rotated zero or more positions. Find its minimum in logarithmic time.
Examples
Example 1
nums = [3,4,5,1,2]
Output: 1
Example 2
nums = [4,5,6,7,0,1,2]
Output: 0
Constraints
- 1 <= nums.length <= 1000
- -1000 <= nums[i] <= 1000
Need a hint?
Compare the middle element with the rightmost element.
Asked in real interviews
Candidates reported versions of Find Minimum in Rotated Sorted Array from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Keep an inclusive search interval. If nums[mid] > nums[right], the minimum lies strictly right of mid, so move left to mid + 1. Otherwise mid may be the minimum, so set right to mid. Return the value when both bounds meet.
Complexity
O(log n) time and O(1) space.
Python reference solution
def findMin(nums):
left, right = 0, len(nums) - 1
while left < right:
middle = (left + right) // 2
if nums[middle] > nums[right]:
left = middle + 1
else:
right = middle
return nums[left]
JavaScript solution
function findMin(nums) {
let left = 0, right = nums.length - 1;
while (left < right) {
const middle = left + Math.floor((right - left) / 2);
if (nums[middle] > nums[right]) left = middle + 1;
else right = middle;
}
return nums[left];
}
Java solution
import java.util.*;
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int middle = left + (right - left) / 2;
if (nums[middle] > nums[right]) left = middle + 1;
else right = middle;
}
return nums[left];
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMin(vector<int> &nums) {
int left = 0, right = (int)nums.size() - 1;
while (left < right) {
int middle = left + (right - left) / 2;
if (nums[middle] > nums[right]) left = middle + 1;
else right = middle;
}
return nums[left];
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
4,
5,
1,
2
]
]1
[
[
4,
5,
6,
7,
0,
1,
2
]
]0
[
[
11,
13,
15,
17
]
]11
[
[
2,
3,
4,
5,
1
]
]1
[
[
1
]
]1
Drafts are saved per language in this browser when storage is available.