153. Find Minimum in Rotated Sorted Array
## description
## 153. Find Minimum in Rotated Sorted Array
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.
- –[0,1,2,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 of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
1Input: nums = [3,4,5,1,2]
2Output: 1
3Explanation: The original array was [1,2,3,4,5] rotated 3 times.Example 2:
1Input: nums = [4,5,6,7,0,1,2]
2Output: 0
3Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.Example 3:
1Input: nums = [11,13,15,17]
2Output: 11
3Explanation: The original array was [11,13,15,17] and it was rotated 4 times.- –n == nums.length
- –1 <= n <= 5000
- –-5000 <= nums[i] <= 5000
- –All the integers of nums are unique.
- –nums is sorted and rotated between 1 and n times.
Constraints:
## notes
### Intuition
In a rotated sorted array, the minimum element is the pivot point where the rotation occurred. It's the only element where both neighbors are larger (or it's at a boundary).
### Implementation
Use binary search. The stop condition is when the element before and after mid are both greater (or mid is at a boundary). To decide which half to search, compare nums[mid] with nums[r]—if mid is larger, the minimum is in the right half; otherwise, it's in the left half.
### Edge-cases
Boundary checks are essential. When mid is 0 or n-1, we can't compare with neighbors, so include these cases in the stop condition to avoid index out of bounds.
- –Time: O(log n) — binary search halves the range each iteration
- –Space: O(1) — only tracking pointers
### Complexity
## solution
1from typing import List
2
3class Solution:
4 def findMin(self, nums: List[int]) -> int:
5 n = len(nums)
6 l, r = 0, n - 1
7
8 while l <= r:
9 m = (l + r) // 2
10 if (m == 0 or nums[m - 1] > nums[m]) and (m == n - 1 or nums[m + 1] > nums[m]):
11 return nums[m]
12 elif nums[r] < nums[m]:
13 # move towards smaller value
14 l = m + 1
15 else:
16 # move towards smaller value
17 r = m - 1
18 return -1 # shouldn't get here
19
20
21
22
23if __name__ == "__main__":
24 # Include one-off tests here or debugging logic that can be run by running this file
25 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
26 solution = Solution()
27