mediumUnion FindHash TableArrays & Hashing

Longest Consecutive Sequence

mediumTime: O(n)Space: O(n)

Signals to notice

find longest run of consecutive numbersunordered inputO(n) required

Brute force first

Sort and scan for consecutive runs. Sorting is overkill for this problem. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Put all numbers in a hash set. For each number that's a sequence START (n-1 not in set), count consecutive numbers going up. Track the longest run. — each number is visited at most twice. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

Only start counting from the BEGINNING of a sequence (where n-1 doesn't exist in the set). This ensures each element is part of exactly one count, giving total. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Starting a count from every number — that's. The key optimization is skipping numbers that aren't sequence starts. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Arrays & Hashing Pattern