Find Minimum in Rotated Sorted Array II — LeetCode 154 Python Solution
- Problem
- #154
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [1,3,5]
- Output
- 1
Python solution
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[mid] > nums[right]:
left = mid + 1
elif nums[mid] < nums[right]:
right = mid
else:
right -= 1
return nums[left]Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 154. Find Minimum in Rotated Sorted Array II is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 154. Find Minimum in Rotated Sorted Array II?
- LeetCode 154. Find Minimum in Rotated Sorted Array II is rated Hard on LeetCode.
- What topics does LeetCode 154. Find Minimum in Rotated Sorted Array II cover?
- LeetCode 154. Find Minimum in Rotated Sorted Array II is tagged Array and Binary Search on LeetCode.