Skip to content

Commit 0201345

Browse files
committed
Add find-minimum-in-rotated-sorted-array solution
1 parent 979a991 commit 0201345

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// Binary Search
7+
// Time Complexity: O(log n) (Binary search halving the search space each step)
8+
// Space Complexity: O(1) (No extra space except for a few variables)
9+
var findMin = function (nums) {
10+
// Example Rotations:
11+
// nums = [0,1,2,4,5,6,7]
12+
// [4,5,6,7,0,1,2] -> Rotated 4 times
13+
// [0,1,2,4,5,6,7] -> 7 times rotated
14+
15+
// Initial State:
16+
// [4, 5, 6, 7, 0, 1, 2]
17+
// ↑ ↑
18+
// (left) (right)
19+
//
20+
// Find mid:
21+
// [4, 5, 6, 7, 0, 1, 2]
22+
// ↑ 🎯 ↑
23+
// (left) (mid) (right)
24+
//
25+
// If nums[mid] > nums[right], move left to search in the right half:
26+
// [4, 5, 6, 7, 0, 1, 2]
27+
// ↑ ↑
28+
// (left) (right)
29+
30+
let left = 0;
31+
let right = nums.length - 1;
32+
33+
while (left < right) {
34+
let mid = Math.floor((left + right) / 2);
35+
36+
if (nums[mid] > nums[right]) {
37+
// Minimum must be in the right half
38+
// Need to update left to search in the right half
39+
left = mid + 1;
40+
} else {
41+
// Minimum is in the left half (including mid)
42+
// Need to update right to search in the left half
43+
right = mid;
44+
}
45+
}
46+
47+
return nums[left];
48+
};
49+

0 commit comments

Comments
 (0)