AlgoViz

Longest Consecutive Sequence

Medium

Only start counting from sequence heads

In simple words

Put all numbers in a set, then from each number that starts a run, count upward as far as you can.

The idea

Put everything in a set. A number starts a run only if num−1 is absent; from each such start, walk upward counting. Every number is visited at most twice, so it's O(n).

100
4
200
1
3
2
0
1
2
3
4
5

Step 1 of 8. Brute force: from each number, keep searching for the next consecutive one. Values: 100, 4, 200, 1, 3, 2.

1/8
Brute force
timeO(n²)spaceO(n)

Search each run.

1for (const x of nums) {2  let len = 1, cur = x;3  while (set.has(cur + 1)) { cur++; len++; }4  best = Math.max(best, len);5}

Input

array
[100, 4, 200, 1, 3, 2]

Memory

i

Output

best
answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
nums = [100, 4, 200, 1, 3, 2]
Output:
4
Explanation:
1,2,3,4 form a run of length 4.

Example 2

Input:
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output:
9
Explanation:
0..8 is a run of length 9.

Example 3

Input:
nums = [10]
Output:
1
Explanation:
A single number is a run of length 1.

Finished the walkthrough? Add it to your streak.