Find Minimum in Rotated Sorted Array — LeetCode 153 Python Solution
- Problem
- #153
- 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,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times.
Example
- Input
- nums = [3,4,5,1,2]
- Output
- 1
- Explanation
- The original array was [1,2,3,4,5] rotated 3 times.
Python solution
class Solution:
def findMin(self, nums: List[int]) -> int:
if nums[0] <= nums[-1]:
return nums[0]
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[0] <= nums[mid]:
left = mid + 1
else:
right = mid
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 153. Find Minimum in Rotated Sorted Array 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
On study lists
This problem is on Blind 75, NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 153. Find Minimum in Rotated Sorted Array?
- LeetCode 153. Find Minimum in Rotated Sorted Array is rated Medium on LeetCode.
- What topics does LeetCode 153. Find Minimum in Rotated Sorted Array cover?
- LeetCode 153. Find Minimum in Rotated Sorted Array is tagged Array and Binary Search on LeetCode.