Skip to content

Commit 091c502

Browse files
committed
longest consecutive sequence solution
1 parent 942bfa7 commit 091c502

File tree

1 file changed

+22
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)