Find First and Last Position of Element in Sorted Array LeetCode solution in JavaScript

1
var searchRange = function (nums, target) {
2
if (nums.length === 1) return nums[0] === target ? [0, 0] : [-1, -1];
3

4
const findFirstInstance = (left, right) => {
5
if (left === right) return left;
6
var pivot;
7
while (left < right) {
8
if (left === pivot) left += 1;
9
pivot = Math.floor((left + right) / 2);
10
if (nums[pivot] === target) {
11
if (nums[pivot - 1] !== target) return pivot;
12
return findFirstInstance(left, pivot - 1);
13
}
14
if (nums[pivot] > target) right = pivot;
15
else left = pivot;
16
}
17
};
18
const findLastInstance = (left, right) => {
19
if (left === right) return left;
20
var pivot;
21
while (left < right) {
22
if (left === pivot) left += 1;
23
pivot = Math.floor((left + right) / 2);
24
if (nums[pivot] === target) {
25
if (nums[pivot + 1] !== target) return pivot;
26
return findLastInstance(pivot + 1, right);
27
}
28
if (nums[pivot] > target) right = pivot;
29
else left = pivot;
30
}
31
};
32

33
var left = 0,
34
right = nums.length - 1,
35
pivot;
36

37
while (left < right) {
38
if (left === pivot) left += 1;
39
pivot = Math.floor((left + right) / 2);
40
if (nums[pivot] === target) {
41
var first =
42
nums[pivot - 1] !== target ? pivot : findFirstInstance(left, pivot - 1);
43
var last =
44
nums[pivot + 1] !== target ? pivot : findLastInstance(pivot + 1, right);
45
return [first, last];
46
}
47
if (nums[pivot] > target) right = pivot;
48
else left = pivot;
49
}
50

51
return [-1, -1];
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0