DSA Visualizer · 25 visualizationsLongest Consecutive Sequence
Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Put every value in a set so “is x in the array?” is O(1). Look for numbers that start a run — no x−1 in the set.
Problem
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Examples
The longest run is [1,2,3,4]
Constraints
- 0 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
Intuition
Put every value in a hash set for O(1) membership checks. A value only needs to be examined as the *start* of a run — one whose predecessor (value − 1) isn't in the set. From each start, count forward while the next value is present. Every number gets counted inside at most one run across the whole pass, so the total work is still O(n) even though it looks like nested loops.
Brute force → Optimal
Sort the array, then scan once counting the longest run of adjacent values that differ by 1.
Hash set of all values; only start counting from values with no predecessor in the set, then count forward.
Complexity
Edge cases
- Empty array: the answer is 0 — there's no run to find.
- Duplicate values, e.g. the two 0s in [0,3,7,2,5,8,4,6,0,1]: the set collapses them to one value, so they don't inflate the run length.
Common mistakes
- Starting the forward count from every value instead of only values with no predecessor — that turns the algorithm back into O(n²) on a long run.
- Sorting without first deduplicating, which can overcount a run when the same value repeats.