153. Find Minimum in Rotated Sorted Array
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Binary Search
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven a sorted array that has been rotated at some unknown pivot point, find the minimum element. All values are unique and the array was originally sorted in ascending order.
Approach
- Use binary search by comparing
nums[mid]tonums[r](the right boundary) to decide which half contains the minimum. - If
nums[mid] > nums[r], the left half is fully sorted and the minimum must lie in the right half, so movel = mid + 1. - Otherwise the right half (including
mid) is the portion that wraps around or is fully sorted ending atr, so keepr = mid. - When
l == rthe pointers converge on the minimum element.
#include <vector>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0, r = static_cast<int>(nums.size()) - 1;
while (l < r) {
int mid = l + (r - l) / 2;
// If mid value exceeds the rightmost value, the rotation point
// (and thus the minimum) lies in the right half.
if (nums[mid] > nums[r]) {
l = mid + 1;
} else {
// mid could itself be the minimum, so keep it in range.
r = mid;
}
}
return nums[l]; // l == r, converged on the minimum
}
};
Time O(log n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
int l=0, r=nums.size()-1;
while(l<r){
int lval=nums[l];
int rval=nums[r];
if(lval<rval){
return lval;
}
int mid=(l+r)/2;
if(nums[mid]>=lval){
l=mid+1;
}
else{
r=mid;
}
}
return nums[l];
}
};
// Time: O(log n)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.