128. Longest Consecutive Sequence
My accepted JavaScript solution to LeetCode problem 128, Longest Consecutive Sequence, running in 34ms.
- Difficulty: Medium
- JavaScript
- Runtime 34ms
- Memory 81.3MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 34ms, memory 81.3MB, accepted 2025-12-24.
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
const set = new Set(nums);
let maxLen = 0;
for (const num of set) {
// Only start counting if num is the start of a sequence
if (!set.has(num - 1)) {
let curr = num;
let len = 1;
while (set.has(curr + 1)) {
curr++;
len++;
}
maxLen = Math.max(maxLen, len);
}
}
return maxLen;
};