Skip to content

Commit 0306d11

Browse files
author
Kohei Asai
authored
34. Find First and Last Position of Element in Sorted Array (#86)
1 parent 3b4ecde commit 0306d11

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import searchRange from "./findFirstAndLastPositionOfElementInSortedArray";
2+
3+
const TEST_CASES = new Map<[number[], number], [number, number]>([
4+
[[[5, 7, 7, 8, 8, 10], 8], [3, 4]],
5+
[[[5, 7, 7, 8, 8, 10], 6], [-1, -1]],
6+
[[[2, 2], 2], [0, 1]]
7+
]);
8+
9+
describe("34. Find First and Last Position of Element in Sorted Array", () => {
10+
for (const [args, expected] of TEST_CASES) {
11+
test(`when [${args[0].join(", ")}], ${args[1]}`, () => {
12+
expect(searchRange(args[0], args[1])).toEqual(expected);
13+
});
14+
}
15+
});
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// 34. Find First and Last Position of Element in Sorted Array
2+
// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
3+
export default function searchRange(
4+
nums: number[],
5+
target: number
6+
): [number, number] {
7+
// binary search to find the first index
8+
let from = 0;
9+
let to = nums.length;
10+
11+
// loop until the search range shrinks to be from + 2 === to
12+
while (to - from >= 3) {
13+
const middle = Math.floor((from + to) / 2);
14+
15+
if (nums[middle] >= target) {
16+
to = middle + 1;
17+
} else {
18+
from = middle;
19+
}
20+
}
21+
22+
// nums[from] or nums[to - 1] may point the target value
23+
// otherwise, there's no target value
24+
let first: number;
25+
26+
if (nums[from] === target) {
27+
first = from;
28+
} else if (nums[to - 1] === target) {
29+
first = to - 1;
30+
} else {
31+
return [-1, -1];
32+
}
33+
34+
// binary search to find the last index
35+
from = first >= 0 ? first : 0;
36+
to = nums.length;
37+
38+
// do the same binary search for the last index
39+
while (to - from >= 3) {
40+
const middle = Math.floor((from + to) / 2);
41+
42+
if (nums[middle] <= target) {
43+
from = middle;
44+
} else {
45+
to = middle + 1;
46+
}
47+
}
48+
49+
let last: number;
50+
51+
// pick to-value first because the values both from and to point could be target
52+
if (nums[to - 1] === target) {
53+
last = to - 1;
54+
} else if (nums[from] === target) {
55+
last = from;
56+
}
57+
58+
return [first, last!];
59+
}

0 commit comments

Comments
 (0)