Skip to content

Commit 5020e65

Browse files
authored
Create 0034-find-first-and-last-position-of-element-in-sorted-array.js
Solved find-first-and-last-position-of-element-in-sorted-array in js.
1 parent 794f343 commit 5020e65

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Binary Search
3+
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
4+
* Time O(log(n)) | Space O(1)
5+
* @param {number[]} nums
6+
* @param {number} target
7+
* @return {number[]}
8+
*/
9+
var searchRange = function(nums, target) {
10+
11+
const result = [];
12+
13+
result.push(binarySearch(true));
14+
result.push(binarySearch(false));
15+
16+
function binarySearch(leftBias) {
17+
let left = 0;
18+
let right = nums.length - 1;
19+
let index = -1;
20+
21+
while(left <= right) {
22+
23+
const mid = Math.floor((left+right)/2);
24+
25+
if(target > nums[mid]) {
26+
left = mid+1;
27+
}
28+
if(target < nums[mid]) {
29+
right = mid-1;
30+
}
31+
// this is the meat of the code
32+
if(target === nums[mid]) {
33+
if(leftBias) {
34+
index = mid;
35+
right = mid - 1;
36+
} else {
37+
index = mid;
38+
left = mid + 1;
39+
}
40+
}
41+
}
42+
43+
return index;
44+
}
45+
46+
return result;
47+
};

0 commit comments

Comments
 (0)