Skip to content

Commit 054e552

Browse files
committed
longest-consecutive-sequence
1 parent f3326a8 commit 054e552

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 128. Longest Consecutive Sequence
3+
* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
4+
*
5+
* You must write an algorithm that runs in O(n) time.
6+
* https://leetcode.com/problems/longest-consecutive-sequence/description/
7+
*/
8+
function longestConsecutive(nums: number[]): number {
9+
const set = new Set(nums);
10+
const sorted = [...set].sort((a, b) => a - b);
11+
12+
if (sorted.length === 0) {
13+
return 0;
14+
}
15+
16+
let longestSequence = 1;
17+
let currentSequence = 1;
18+
for (let i = 0; i - 1 < sorted.length; i++) {
19+
if (Math.abs(sorted[i + 1] - sorted[i]) === 1) {
20+
currentSequence++;
21+
} else {
22+
if (currentSequence > longestSequence) {
23+
longestSequence = currentSequence;
24+
}
25+
currentSequence = 1;
26+
}
27+
}
28+
29+
return longestSequence;
30+
}
31+
32+
// O(n) time
33+
// O(n) space

0 commit comments

Comments
 (0)