Here’s the LeetCode-ready Java implementation for #154 Find Minimum in Rotated Sorted Array II.
🧠 Core Idea
This is binary search, but duplicates break the usual “discard half” logic. We compare
“nums[mid]” with
“nums[right]”:
Condition Meaning Action
“nums[mid] < nums[right]” Min is in left half (incl. mid)
“right = mid”
“nums[mid] > nums[right]” Min is in right half
“left = mid + 1”
“nums[mid] == nums[right]” Can’t decide (duplicates)
“right–” (shrink safely)
Why
“right–” is safe: If
“nums[mid] == nums[right]”, even if
“nums[right]” were the min, there’s an identical value at
“mid”, so we never lose the true minimum.
✅ Java Solution (LeetCode format)
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 is in the left half (mid could be the min) right = mid; } else if (nums[mid] > nums[right]) { // Minimum is in the right half left = mid + 1; } else { // nums[mid] == nums[right], ambiguous due to duplicates right--; } } return nums[left]; }}
📊 Complexity
- Time:
“O(log n)” average / best case → degrades to
“O(n)” worst case (e.g.,
“[1,1,1,1,1]”) - Space:
“O(1)”
🔍 Quick Dry Run
nums = [2,2,2,0,1]
left=0, right=4, mid=2 → nums[2]=2 > nums[4]=1 → left=3
left=3, right=4, mid=3 → nums[3]=0 < nums[4]=1 → right=3
left==right → return nums[3] = 0 ✅
💡 vs. LeetCode 153 (no duplicates)
- 153: strict comparison, always
“O(log n)”,
“right = mid” /
“left = mid + 1” only. - 154: adds the
“nums[mid] == nums[right]” branch →
“right–”, which is why worst case can be
“O(n)”.
Want me to add a recursive version, test cases, or a visual diagram of the search range?