Leetcode 153. Find Minimum in Rotated Sorted Array
Suppose an array of length n
sorted in ascending order is rotated between 1
and n
(inclusive) times. For example, the array nums = [0,1,2,4,5,6,7]
might become:
[4,5,6,7,0,1,2]
if it was rotated 4
times.[0,1,2,4,5,6,7]
if it was rotated 7
times (i.e., not rotated at all).You are given a rotated sorted array nums
of unique elements and need to return the minimum element of this array.
You must write an algorithm that runs in O(log n)
time.
Given the constraints and the requirement for logarithmic time complexity, a binary search approach is suitable. Here’s the strategy:
left
and right
, to perform the binary search.mid = left + (right - left) / 2
.nums[mid]
with nums[right]
to determine which part of the array to search next:
nums[mid] > nums[right]
, then the smallest value must be to the right of mid
(including right
itself).nums[mid] <= nums[right]
, then the smallest value is to the left of mid
, including the middle element itself.left
equals right
, where the minimum element will be located at index left
.public class Solution {
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
// Minimum must be in the right part
left = mid + 1;
} else {
// Minimum could be at mid or in the left part
right = mid;
}
}
return nums[left];
}
}
The time complexity of this solution is O(log n)
, where n
is the number of elements in the array. This is due to the binary search approach that reduces the search space by approximately half in each iteration.
The space complexity is O(1)
since no extra space is used besides a few variables.
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?