153. Find Minimum in Rotated Sorted Array
Intuition
Complexity
Space Complexity
Time Complexity
Code
public int findMin(int[] nums) {
// If the array is already sorted, the first element is the minimum
if (nums[0] <= nums[nums.length - 1]) return nums[0];
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
// Check if mid is the pivot point (greater than next element)
boolean isPivotPoint = (mid + 1 < nums.length && nums[mid] > nums[mid + 1]);
if (isPivotPoint) {
return nums[mid + 1]; // Found the minimum
}
// If mid element is less than the last element, the min is on the left
if (nums[mid] < nums[nums.length - 1]) {
right = mid - 1;
} else {
// Else, the min is on the right
left = mid + 1;
}
}
return -1; // This should not be reached if input is valid
}
Last updated