128. Longest Consecutive Sequence
At a Glance
- Topic: arrays-hashing
- Pattern: Hash Set Sequence
- Difficulty: Medium
- Companies: Google, Amazon, Meta, Bloomberg, Microsoft
- Frequency: High
- LeetCode: 128
Problem (one-liner)
Given an unsorted array of integers numbers, return the length of the longest run of consecutive integers in value space (not index order). Algorithm must be O(n) expected time.
Recognition Cues
- "Consecutive integers", "longest streak", unsorted array
- Sort would be
O(n log n)— need set + start only from sequence beginnings
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — for each element, scan
x+1, x+2, …—O(n³)worst if naive. - Better — sort, scan runs —
O(n log n)time. - Optimal — hash set of all numbers; for each
value, ifvalue-1not in set, walk upward counting —O(n)time /O(n)space.
Optimal Solution
Go
package main
func longestConsecutive(numbers []int) int {
seen := make(map[int]struct{}, len(numbers))
for _, value := range numbers {
seen[value] = struct{}{}
}
longest := 0
for value := range seen {
if _, hasPrev := seen[value-1]; hasPrev {
continue
}
length := 0
current := value
for {
if _, exists := seen[current]; !exists {
break
}
length++
current++
}
if length > longest {
longest = length
}
}
return longest
}JavaScript
function longestConsecutive(numbers) {
const seen = new Set(numbers);
let longest = 0;
for (const value of seen) {
if (seen.has(value - 1)) {
continue;
}
let length = 0;
let current = value;
while (seen.has(current)) {
length++;
current++;
}
if (length > longest) {
longest = length;
}
}
return longest;
}Walkthrough
Input: numbers = [100, 4, 200, 1, 3, 2]
| value tried | value-1 in set? | role | walk result |
|---|---|---|---|
| 100 | 99 no | start | 100 only → len 1 |
| 4 | 3 yes | skip (mid) | — |
| 200 | 199 no | start | 200 only → len 1 |
| 1 | 0 no | start | 1,2,3,4 → len 4 |
Answer 4.
Edge Cases
- Empty array → 0.
- Single element → 1.
- Duplicates — set collapses them; length unchanged.
Pitfalls
- Counting from every element →
O(n²)time; must skip unless start of chain. - Using sort when linear set solution exists.
Similar Problems
- 217. Contains Duplicate — set of values.
- 001. Two Sum — complementary lookups in a map.
- 049. Group Anagrams — equivalence classes via keys.
Variants
- Longest arithmetic progression (different technique).
- Count all consecutive sequences above length threshold.
Mind-Map Tags
#hashset #sequence #on-time #integers #chain-start
Last updated on
Spotted something unclear or wrong on this page?