153. Find Minimum in Rotated Sorted Array
Explanation
To find the minimum element in a rotated sorted array, we can utilize a modified binary search algorithm. The idea is to compare the middle element of the array with the first and last elements to determine which half of the array to discard. This way, we can focus on the unsorted half where the minimum element lies.
- Initialize two pointers,
left
andright
, pointing to the start and end of the array respectively. - Perform binary search until
left
andright
converge, indicating that the minimum element has been found. - At each step, compare the middle element with the first and last elements to determine which half is unsorted and update
left
orright
accordingly. - Return the element at the
left
index, which will be the minimum element.
Time complexity: O(log n) Space complexity: O(1)
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right]) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[left];
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.