Find Minimum in Rotated Sorted Array II
LeetCode 154 · Hard · solution, intuition & step-by-step walkthrough
Equal ⇒ high −= 1.
This is how I solved Find Minimum in Rotated Sorted Array II (LeetCode 154), a hard problem from the Rotated Sorted Array pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same comparison with the right end, plus one case for duplicates: when nums[mid] equals nums[high] you can't tell which side holds the minimum, but you can safely drop high because mid has the same value.
Approach
- 1
nums[mid] > nums[high] → minimum is right: low = mid + 1.
- 2
nums[mid] < nums[high] → high = mid.
- 3
Equal → high −= 1.
- 4
Return nums[low].
How I solved it
Binary search with duplicatesPythonO(log n) avg
class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
high= len(nums)-1
while low<high:
mid = (low+high)//2
#2,2,2,0,1 if nums[mid]>nums[high],smallest will be on the right half
if nums[mid]>nums[high]:
low = mid+1
#1,3,5 if nums[mid]<nums[high], the lowest must be on the left half, include mid 3,1,3 to handle this special case to include mid as well
elif nums[mid]<nums[high]:
high = mid
#10,1,10,10 reduce the search space if nums[mid] and nums[high] are equal
else:
high = high-1
return nums[low]Find Minimum in Rotated Sorted Array II — FAQ
What is the intuition behind Find Minimum in Rotated Sorted Array II?
Same comparison with the right end, plus one case for duplicates: when nums[mid] equals nums[high] you can't tell which side holds the minimum, but you can safely drop high because mid has the same value.
How do you solve Find Minimum in Rotated Sorted Array II (LeetCode 154)?
1. nums[mid] > nums[high] → minimum is right: low = mid + 1. 2. nums[mid] < nums[high] → high = mid. 3. Equal → high −= 1. 4. Return nums[low].
What is the time and space complexity of Find Minimum in Rotated Sorted Array II?
Time: O(log n) average, O(n) worst. Space: O(1). (Accepted approach: Binary search with duplicates.)
What are common mistakes in Find Minimum in Rotated Sorted Array II?
Don't jump high = mid on equality — the minimum could be between.