The Find Minimum in Rotated Sorted Array II problem involves finding the minimum element in a rotated sorted array that may contain duplicates. The goal is to solve this in O(log N)
time in the best case, but it may degrade to O(N)
in the presence of duplicates.
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; // Minimum is in the left half
} else if (nums[mid] > nums[right]) {
left = mid + 1; // Minimum is in the right half
} else {
right--; // Handle duplicates by reducing the search space
}
}
return nums[left]; // Minimum element
}
}
O(log N)
โ Halving the search space at each step.O(N)
โ When duplicates force a linear scan.Input: nums = [2,2,2,0,1]
Output: 0
Explanation:
- The minimum element in the array is 0.
nums[mid] == nums[right]
.