Longest Consecutive Sequence

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Longest Consecutive Sequence

Approach

Insert all numbers into a Set for O(1) lookup. For each number, check if it is the start of a sequence (num - 1 not in Set). If so, count consecutive numbers upward. Track the longest sequence found across all starting points.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Hash Set Lookup

Why It Works

Only starting sequence exploration from true sequence starts (where num - 1 is absent) ensures each element is visited at most twice total, achieving O(n) despite the nested while loop.

Updated Feb 2026