Skip to content

Commit ba3c3cb

Browse files
committed
solve: longest consecutive sequence
1 parent 3abf25f commit ba3c3cb

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* TC: O(n)
3+
* SC: O(n)
4+
* */
5+
function longestConsecutive(nums: number[]): number {
6+
const consecutives = [...new Set(nums.sort((a, b) => b - a))];
7+
const n = consecutives.length;
8+
9+
if (n === 0) {
10+
return 0;
11+
}
12+
13+
if (n === 1) {
14+
return 1;
15+
}
16+
17+
const bucket = [...Array(n)].map((): Set<number> => new Set());
18+
19+
let cursor = 0;
20+
21+
for (let i = 0; i < n; i++) {
22+
const current = consecutives[i];
23+
const left = consecutives[i - 1];
24+
const right = consecutives[i + 1];
25+
26+
const isLeft = left !== undefined && left - current === 1;
27+
const isRight = right !== undefined && current - right === 1;
28+
29+
const isConsecutive = isLeft || isRight;
30+
31+
if (isConsecutive) {
32+
bucket[cursor].add(current);
33+
34+
if (isLeft && !isRight) {
35+
cursor++;
36+
}
37+
} else {
38+
cursor++;
39+
40+
continue;
41+
}
42+
}
43+
44+
const total = bucket.reduce(
45+
(acc, cur) => (acc > cur.size ? acc : cur.size),
46+
0,
47+
);
48+
49+
return total === 0 ? 1 : total;
50+
}
51+
52+
const t1 = longestConsecutive([100, 4, 200, 1, 3, 2]);
53+
console.info("πŸš€ : tolluset.ts:5: t1=", t1); // 4
54+
55+
const t2 = longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]);
56+
console.info("πŸš€ : tolluset.ts:8: t2=", t2); // 9
57+
58+
const t3 = longestConsecutive([9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6]);
59+
console.info("πŸš€ : tolluset.ts:40: t3=", t3); // 7
60+
61+
const t4 = longestConsecutive([-6, -1, -1, 9, -8, -6, -6, 4, 4, -3, -8, -1]);
62+
console.info("πŸš€ : tolluset.ts:59: t4=", t4); //1

0 commit comments

Comments
Β (0)