Longest Consecutive Sequence
Longest run of consecutive integers in unsorted array — Set + only start at run heads for O(n) average.
- dsa
- hashmap
- interview
- Meta
- Amazon
The problem
Unsorted integers. Return length of the longest consecutive elements sequence. Algorithm should run in O(n).
[100,4,200,1,3,2] → 4 // 1,2,3,4
[0,3,7,2,5,8,4,6,0,1] → 9
Brute: sort unique
function longestConsecutiveSort(nums: number[]): number {
if (!nums.length) return 0;
const a = [...new Set(nums)].sort((x, y) => x - y);
let best = 1;
let cur = 1;
for (let i = 1; i < a.length; i++) {
if (a[i] === a[i - 1] + 1) {
cur++;
best = Math.max(best, cur);
} else cur = 1;
}
return best;
}
| Time | O(n log n) |
| Space | O(n) |
Good baseline; problem asks for O(n).
Optimal: Set + start of streak only
- Put all values in a Set.
- For each
x, ifx-1is not in the set,xstarts a sequence. - Count upward while
x+lenexists. - Track max length.
function longestConsecutive(nums: number[]): number {
const set = new Set(nums);
let best = 0;
for (const x of set) {
if (set.has(x - 1)) continue; // not a start
let len = 1;
while (set.has(x + len)) len++;
best = Math.max(best, len);
}
return best;
}
| Time | O(n) average — each number visited constant times in while |
| Space | O(n) |
Why O(n)?
Inner while only runs for streak starts; across all starts, each element is scanned once as a streak member.
Edge cases
- Empty → 0
- All duplicates → 1
- Negatives
- Single element
Common mistakes
- Starting a count from every number → O(n²)
- Using object keys and forgetting negatives
- Sorting and claiming O(n)
Interview delivery
- O(n) required.
- Set membership.
- Only expand from sequence starts.
- Amortized linear proof one-liner.
- Empty case.
Mental model
Put numbers in a hash set so x+1 probes are O(1). Only start counting from numbers that have no predecessor — each streak is scanned once, giving amortized linear time despite the nested loop shape.
Proof sketch
Every number is the start of at most one streak check. Inside the while, each number is visited as a member at most once across the whole algorithm. Total probes O(n).
Out-loud answer
“O(n) longest consecutive run. Set of values; for each x missing x-1, count upward. Track max length. Sorting is simpler but O(n log n). Empty → 0.”
Complexity table
| Approach | Time | Space | Meets O(n) ask? |
|---|---|---|---|
| Sort unique | O(n log n) | O(n) | no |
| Set + start only | O(n) avg | O(n) | yes |
| Union-find | O(n α(n)) | O(n) | yes, heavier |
Interview delivery
- Need O(n).
- Hash set.
- Expand only from streak heads.
- Amortized linear.
- Empty and duplicates.