Skip to content

Commit 94f2c10

Browse files
committed
longest consecutive seq solution
1 parent f9ab862 commit 94f2c10

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* requirement: return result in linear time (O(n))
3+
*/
4+
function longestConsecutive(nums: number[]): number {
5+
if (nums.length === 0) return 0;
6+
7+
const numSet = new Set(nums); // O(1) lookups
8+
let maxLength = 0;
9+
10+
for (const num of numSet) {
11+
// key: determine the "start" of a consecutive sequence.
12+
// approach: if num - 1 doesn't exist in the set → num is the start of a sequence.
13+
if (!numSet.has(num - 1)) {
14+
let currentNum = num;
15+
let currentLength = 1;
16+
17+
// count consecutive numbers
18+
while (numSet.has(currentNum + 1)) {
19+
currentNum++;
20+
currentLength++;
21+
}
22+
23+
maxLength = Math.max(maxLength, currentLength);
24+
}
25+
}
26+
return maxLength;
27+
}

0 commit comments

Comments
 (0)