Find Minimum in Rotated Sorted Array II - Problem
Imagine you have a sorted array that has been rotated at some pivot point, and it may contain duplicate elements. Your task is to find the minimum element in this rotated array as efficiently as possible.
What is array rotation? Rotating an array means moving elements from the end to the beginning. For example:
- Original:
[0,1,4,4,5,6,7] - Rotated 4 times:
[4,5,6,7,0,1,4] - Rotated 7 times:
[0,1,4,4,5,6,7](back to original)
The Challenge: Unlike the version without duplicates, the presence of duplicate elements makes it impossible to always determine which half of the array to search in O(log n) time. Sometimes we need to handle the worst-case scenario where duplicates appear at critical positions.
Goal: Return the minimum element while minimizing the number of operations.
Input & Output
example_1.py โ Basic Rotation
$
Input:
[2,2,2,0,1]
โบ
Output:
0
๐ก Note:
The array was originally [0,1,2,2,2] and rotated. The minimum element is 0.
example_2.py โ Heavy Duplicates
$
Input:
[1,3,3]
โบ
Output:
1
๐ก Note:
The array has duplicates but no rotation. The minimum element is 1.
example_3.py โ All Same Elements
$
Input:
[3,3,3,3,3]
โบ
Output:
3
๐ก Note:
All elements are the same, so the minimum is 3. This is the worst case for binary search.
Constraints
- n == nums.length
- 1 โค n โค 5000
- -5000 โค nums[i] โค 5000
- nums is sorted and rotated between 1 and n times
- Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?
Visualization
Tap to expand
Understanding the Visualization
1
Set Boundaries
Place markers at the leftmost and rightmost books you need to consider
2
Check Middle
Look at the book in the middle of your current range
3
Make Decision
Compare middle book with rightmost book to determine which half likely contains the minimum
4
Handle Ties
When middle and right books have same page count, remove the rightmost duplicate to make progress
Key Takeaway
๐ฏ Key Insight: Binary search with duplicate handling - when we can't decide which half to search due to equal elements, we sacrifice one element from the boundary to make progress, maintaining logarithmic performance in most cases.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code