-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-min-rotated.ts
More file actions
34 lines (32 loc) · 893 Bytes
/
Copy pathfind-min-rotated.ts
File metadata and controls
34 lines (32 loc) · 893 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 153. Find Minimum in Rotated Sorted Array (Medium)
* Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
*
* A sorted array of unique values was rotated at an unknown pivot. Return the
* minimum element. Must run in O(log n).
*
* Example:
* Input: nums = [4, 5, 6, 7, 0, 1, 2]
* Output: 0
*
* Approach:
* Binary search for the pivot. Compare nums[mid] with nums[hi]: if
* nums[mid] > nums[hi] the minimum lies strictly to the right of mid; else it
* is at mid or to its left. Converge until lo === hi, which is the minimum.
*
* Time: O(log n)
* Space: O(1)
*/
export function findMin(nums: number[]): number {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] > nums[hi]) {
lo = mid + 1;
} else {
hi = mid;
}
}
return nums[lo];
}