Find Minimum In Rotated Sorted Array II Problem
Description
LeetCode Problem 154.
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
- [4,5,6,7,0,1,4] if it was rotated 4 times.
- [0,1,4,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [1,3,5]
Output: 1
Example 2:
Input: nums = [2,2,2,0,1]
Output: 0
Constraints:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- nums is sorted and rotated between 1 and n times.
Solution
Approach: Binary Search, Shrinking on Ties
This is the binary search for the array without duplicates, plus one extra case. Compare the middle element with the last element of the current range [left, right]:
nums[mid] > nums[right]: there is a drop aftermid, so the minimum is strictly to the right:left = mid + 1.nums[mid] < nums[right]:nums[mid..right]is sorted, so the minimum ismidor to its left:right = mid.nums[mid] == nums[right]: we cannot tell which side the drop is on. In[3, 3, 1, 3]the minimum is right ofmid, and in[3, 1, 3, 3, 3]it is left ofmid. But we can safely dropnums[right]: if it was the minimum,nums[mid]has the same value and is still in the range. Soright -= 1.
When left == right, that element is the minimum.
The tie case is what makes this problem harder than the version with unique values. Moving left on a tie, or discarding half the range, can skip the minimum. Taking one step from the right is the only move that is always safe.
Complexity: O(log n) time when there are few duplicates, but O(n) in the worst case (for example, all elements equal but one), where n is the length of nums; O(1) space. No algorithm can do better in the worst case, because the single smaller element could be anywhere.
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
# The minimum is always inside nums[left..right].
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1 # the drop is to the right of mid, so mid is not the minimum
elif nums[mid] < nums[right]:
right = mid # nums[mid..right] is sorted, so the minimum is at mid or to its left
else:
right -= 1 # equal: cannot tell the side, but nums[mid] keeps the same value in range
return nums[left]
Now write it from memory
Close the write-up and solve it yourself against the tests.