Leetcode 153. Find Minimum in Rotated Sorted Array
You are given an integer array nums
sorted in ascending order (with distinct values), and a rotation of nums
, where nums
is rotated at an unknown pivot index k
(0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
.
For example, the array nums = [0,1,2,4,5,6,7]
might be rotated at pivot index 3
and become [4,5,6,7,0,1,2]
.
Return the minimum element of this rotated array.
You must write an algorithm that runs in O(log n)
time.
nums = [3,4,5,1,2]
1
nums = [4,5,6,7,0,1,2]
0
nums = [11,13,15,17]
11
To find the minimum element in a rotated sorted array in (O(\log n)) time, we can utilize a modified binary search approach:
left
to 0 and right
to n-1
.left < right
, compute the mid
index.nums[mid] > nums[right]
, it means the smallest value is to the right of mid
, so move left
to mid + 1
.nums[mid] < nums[right]
, it means the smallest value is to the left of mid
(including mid
itself), so move right
to mid
.left == right
, the smallest value is found.The algorithm performs binary search, so the time complexity is (O(\log n)).
#include <vector>
#include <iostream>
class Solution {
public:
int findMin(std::vector<int>& nums) {
int left = 0, right = nums.size() - 1;
// Binary search for the smallest element
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
// The minimum is to the right of mid
left = mid + 1;
} else {
// The minimum can be at mid or to the left of mid
right = mid;
}
}
return nums[left];
}
};
int main() {
Solution sol;
// Test Cases
std::vector<int> nums1 = {3, 4, 5, 1, 2};
std::vector<int> nums2 = {4, 5, 6, 7, 0, 1, 2};
std::vector<int> nums3 = {11, 13, 15, 17};
std::cout << sol.findMin(nums1) << std::endl; // Output: 1
std::cout << sol.findMin(nums2) << std::endl; // Output: 0
std::cout << sol.findMin(nums3) << std::endl; // Output: 11
return 0;
}
This solution successfully finds the minimum element in a rotated sorted array using an efficient (O(\log n)) approach with binary search.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?