#154
Find Minimum in Rotated Sorted Array II
HardArrayBinary SearchBinary SearchTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a modified binary search allows us to efficiently find the minimum element in the rotated sorted array, even with duplicates. This method reduces the number of comparisons needed.
⚙️
Algorithm
6 steps- 1Step 1: Initialize left and right pointers to the start and end of the array.
- 2Step 2: While left is less than or equal to right, calculate the mid index.
- 3Step 3: If the middle element is greater than the right element, the minimum must be in the right half, so move left to mid + 1.
- 4Step 4: If the middle element is less than the right element, the minimum is in the left half or could be mid, so move right to mid.
- 5Step 5: If the middle element is equal to the right element, decrement right to skip duplicates.
- 6Step 6: When left equals right, return the element at that index.
solution.py17 lines
1# Full working Python code
2
3def findMin(nums):
4 left, right = 0, len(nums) - 1
5 while left < right:
6 mid = (left + right) // 2
7 if nums[mid] > nums[right]:
8 left = mid + 1
9 elif nums[mid] < nums[right]:
10 right = mid
11 else:
12 right -= 1
13 return nums[left]
14
15# Example usage
16print(findMin([1, 3, 5])) # Output: 1
17print(findMin([2, 2, 2, 0, 1])) # Output: 0ℹ
Complexity note: The time complexity is O(n) in the worst case due to the presence of duplicates, which can lead to a linear scan in some scenarios. However, the average case is O(log n) when duplicates are not present.
- 1The presence of duplicates can complicate the binary search approach, requiring careful handling to avoid infinite loops.
- 2Understanding the properties of rotated sorted arrays is crucial for applying binary search effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.