Longest Consecutive Sequence Visualizer & Step-by-Step Algorithm Solution

Find length of longest contiguous integer streak in O(n) using a hash set.

Category: arrays | Difficulty: Medium

Tags: Hash Set, Streak, O(n)

Longest Consecutive Sequence

Hash Set Elements
100
4
200
1
3
2
100%
state
numnull
isStartnull
currentnull
length0
maxSequence0
Initialize Set
1/23
Explanation

Constructed Hash Set with 6 unique elements: {100, 4, 200, 1, 3, 2}.

Source Code
1function longestConsecutive(nums) {
2 if (nums.length === 0) return 0;
3 const set = new Set(nums);
4 let maxSequence = 0;
5 for (const num of set) {
6 if (!set.has(num - 1)) {
7 let current = num;
8 let length = 1;
9 while (set.has(current + 1)) {
10 current++;
11 length++;
12 }
13 maxSequence = Math.max(maxSequence, length);
14 }
15 }
16 return maxSequence;
17}