- We are given an unsorted array of integers and want to find the length of the longest sequence of consecutive numbers.
-
First, we insert all numbers into a Set to allow quick lookups like
βdoes
xexist?β without sorting the array. -
The key intuition is that we only need to start counting sequences from their beginnings.
If a number (
num) has an immediate predecessor (num - 1) in the set, then it cannot be the start of a new sequence β it belongs to a sequence that starts with a smaller number. By skipping all non-starting numbers, we only expand sequences from true starts, so each number is counted once as part of a valid expansion and skipped at most once. -
We then iterate over each number
numin the set:-
If
num - 1exists in the set, we skipnum, since it is not a sequence start and should be handled as part of the sequence that starts with a smaller number and includes it. -
Otherwise,
numis a sequence start:- We treat it as the beginning of a new consecutive sequence.
-
Starting from
currentSeqNumber = num, we repeatedly checkcurrentSeqNumber + 1,currentSeqNumber + 2, β¦ while they exist in the set. For each such number found, we extend the current sequence and increase its length. - When the next consecutive number is not found in the set, the current sequence ends.
-
If
-
After finishing one sequence, we compare its length (
currentStreak) with the best length seen so far (maxStreak):-
If
currentStreak > maxStreak, we updatemaxStreakto this new length. -
Otherwise, we leave
maxStreakunchanged.
maxStreakalways stores the length of the longest consecutive sequence found so far. -
If
-
Time Complexity: O(n)
Each number is inserted into the set once, and for each sequence start we only walk forward through its consecutive elements once. Because we skip non-starting numbers, every element is part of exactly one sequence expansion. -
Space Complexity: O(n)
We store all numbers in the set, and the remaining variables use only constant extra space.
Longest Consecutive Sequence - JS Solution
JSSolution code
const CURRENT = 'current', CURRENT_COLOR = 'blue';
const SEQ_NUM = 'seq_num', SEQ_NUM_COLOR = 'orange';
function visMainFunction(nums) {
initClassProperties();
explanationAndColorSchemaNotifications();
startBatch();
const numSet = new VisSet(nums);
let maxStreak = 0;
makeVisVariable(maxStreak).options({ label: 'maxStreak' }).createVis();
endBatch();
for (const num of numSet) {
startPartialBatch();
const currentVM = numSet.makeVisManagerForMember(num).addClass(CURRENT);
if (numSet.has(num - 1)) {
notification(`
β© Skipping ${makeColoredSpan(num, CURRENT_COLOR)} because its immediate predecessor <code>${num} - 1 = ${num - 1}</code> is also in the set β
so ${makeColoredSpan(num, CURRENT_COLOR)} cannot be a sequence start and should be handled as part of the sequence that began with a smaller number and includes ${makeColoredSpan(num, CURRENT_COLOR)}.
`);
currentVM.removeClass(CURRENT);
endBatch();
continue;
}
currentVM.addClass(SEQ_NUM);
notification(`
π§ Found a sequence start at ${makeColoredSpan(num, CURRENT_COLOR)} β its immediate predecessor <code>${num} - 1 = ${num - 1}</code> is missing from the set,
so this marks the beginning of a new sequence. Weβll now extend it forward by checking consecutive numbers (${num + 1}, ${num + 2}, β¦) while they exist in the set.
`);
let currentSeqNumber = num;
let currentStreak = 1;
while (numSet.has(currentSeqNumber + 1)) {
currentSeqNumber++;
currentStreak++;
notification(`β Adding ${makeColoredSpan(currentSeqNumber, SEQ_NUM_COLOR)} to the current sequence β since it follows the previous number consecutively, it extends the sequence forward.`);
numSet.makeVisManagerForMember(currentSeqNumber).addClass(SEQ_NUM);
}
notification(`π ${currentSeqNumber + 1} is not in the set β the current sequence ends here.`);
if (currentStreak > maxStreak) {
notification(`π Found a new longest sequence with length ${currentStreak} β updating the maximum recorded length to this new length.`);
maxStreak = currentStreak;
} else {
notification(`βΉοΈ Current sequence length ${currentStreak} does not exceed the maximum (${maxStreak}), so the maximum recorded length remains the same.`);
}
clearSequence(num, numSet);
endBatch();
}
notification(`β
<b>Done</b>. Longest consecutive sequence length is <b>${maxStreak}</b>.`);
return maxStreak;
}
function clearSequence(startNum, visNumSet) {
let seqNum = startNum;
startBatch();
while (visNumSet.has(seqNum)) {
visNumSet.makeVisManagerForMember(seqNum).removeAllClasses();
seqNum++;
}
endBatch();
}
function initClassProperties() {
setClassProperties(CURRENT, { borderColor: CURRENT_COLOR });
setClassProperties(SEQ_NUM, { backgroundColor: SEQ_NUM_COLOR });
}
function explanationAndColorSchemaNotifications() {
explanationNotification();
notification(`
π¨ <b>Visual Cues:</b>
<ul>
<li>
${makeColoredSpan(CURRENT_COLOR + ' border', CURRENT_COLOR)} β the <b>current number</b> being evaluated.
</li>
<li>
${makeColoredSpan(SEQ_NUM_COLOR + ' background', SEQ_NUM_COLOR)} β numbers that are part of the <b>current consecutive sequence</b>.
</li>
</ul>
`);
}Solution explanation
Solution explanation
Approach
Time Complexity
Let n be the number of elements in the array.
All numbers are inserted into the Set, resulting in a total insertion time of O(n).
During iteration, we only begin a sequence expansion when the current number num has no immediate predecessor
(num - 1) in the set β meaning itβs a true sequence start. For each such start, we walk forward through all
consecutive numbers (num + 1, num + 2, β¦) while they exist in the set, calculating the length of the current sequence.
Each existence check takes amortized O(1) time.
Each number is counted once as part of a valid expansion and skipped at most once. Hence, the total work across all numbers is linear in the size of the input array, resulting in an overall running time of O(n).
Space Complexity
Let n be the number of elements in the array.
We store all numbers in a Set to enable quick lookups, which requires O(n) space in total.
Apart from this, only a few scalar variables are used, each contributing just O(1) additional space.
Hence, the overall space complexity is O(n).
Visucodize editorial solution titled JS Solution for LeetCode's Longest Consecutive Sequence coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/longest-consecutive-sequence.