codebrew.ai

Longest Consecutive Sequence

Only start counting from a number that has no left neighbor.

Approach

Put everything in a set for O(1) lookups. For each value, only begin a run if value − 1 is absent (it's the start of a streak), then walk value+1, value+2, … counting length. Every element is visited at most twice, giving O(n) despite the nested look.

Time complexity

O(n)

Space complexity

O(n)

Common mistake

Sorting (O(n log n)) — acceptable, but it misses the intended O(n) set-based trick that starts only from run beginnings.

See it run, step by step

Generate an interactive lesson for Longest Consecutive Sequence — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Longest Consecutive Sequence

Related problems