Skip to content

Commit 88e8975

Browse files
committed
add longest-consecutive-sequence solution
1 parent a954889 commit 88e8975

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* TC: O(n)
3+
* SC: O(n)
4+
* */
5+
function longestConsecutive(nums: number[]): number {
6+
if (nums.length === 0) return 0;
7+
8+
const numSet = new Set(nums);
9+
let longest = 0;
10+
11+
for (const num of nums) {
12+
if (numSet.has(num - 1)) {
13+
continue;
14+
}
15+
16+
let length = 1;
17+
while (numSet.has(num + length)) {
18+
length++;
19+
}
20+
21+
longest = Math.max(length, longest);
22+
}
23+
24+
return longest;
25+
}

0 commit comments

Comments
 (0)