Find Minimum in Rotated Sorted Array II - Problem

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.

Input & Output

Example 1 — Basic Rotation
$ Input: nums = [1,3,5]
Output: 1
💡 Note: The array is not rotated, minimum is the first element: 1
Example 2 — With Duplicates
$ Input: nums = [2,2,2,0,1]
Output: 0
💡 Note: Array has duplicates, but minimum is still 0 which appears after the duplicates
Example 3 — All Same Elements
$ Input: nums = [3,3,3,3,3]
Output: 3
💡 Note: All elements are the same, so minimum is 3

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 5000
  • -5000 ≤ nums[i] ≤ 5000
  • nums is sorted and rotated between 1 and n times.
  • nums may contain duplicates

Visualization

Tap to expand
Find Minimum in Rotated Sorted Array II INPUT Sorted Rotated Array (may have duplicates) 1 idx: 0 3 idx: 1 5 idx: 2 This array is already sorted (rotated 0 or n times) Input Array: nums = [1, 3, 5] Goal: Find minimum efficiently using Binary Search O(log n) worst case O(n) for duplicates ALGORITHM STEPS 1 Initialize Pointers left=0, right=2 2 Calculate Mid mid = (0+2)/2 = 1 3 Compare nums[mid],right nums[1]=3 < nums[2]=5 4 Move right pointer right = mid = 1 Binary Search Logic: if nums[mid] > nums[right]: left = mid + 1 elif nums[mid] < nums[right]: right = mid else: right -= 1 (duplicates) FINAL RESULT Binary Search Converges 1 MIN 3 5 left=right=0 Output: 1 OK - Minimum Found Time: O(log n) avg, O(n) worst Space: O(1) Key Insight: Modified binary search handles duplicates by shrinking search space when nums[mid]==nums[right]. The minimum is always in the unsorted half. Compare mid with right to determine which half is sorted. TutorialsPoint - Find Minimum in Rotated Sorted Array II | Optimal Solution
Asked in
Amazon 45 Microsoft 38 Google 32
125.0K Views
Medium Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen