Skip to content

Commit 0be0550

Browse files
committed
solve: find minimum in rotated sorted array
1 parent fed97ea commit 0be0550

File tree

1 file changed

+26
-0
lines changed
  • find-minimum-in-rotated-sorted-array

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var findMin = function (nums) {
6+
let [left, right] = [0, nums.length - 1];
7+
8+
while (left < right) {
9+
const mid = Math.floor((left + right) / 2);
10+
11+
if (nums[mid] > nums[right]) {
12+
// the smallest element is in the right half
13+
left = mid + 1;
14+
} else {
15+
// the smallest element is in the left half or at mid
16+
right = mid;
17+
}
18+
}
19+
20+
return nums[left];
21+
};
22+
23+
/**
24+
* The time complexity of this approach is O(log n), where n is the number of elements in the array.
25+
* This is because we are effectively halving the search space in each step of the binary search.
26+
*/

0 commit comments

Comments
 (0)