Longest Consecutive Sequence
Pattern: Hashing and frequency
Put every value in a set, and walk upwards only from values that start a run (x - 1 missing). Each value is visited once, so it is O(n).
The problem
You are given an unsorted array of whole numbers, possibly with repeats. Return the length of the longest run of values
that follow each other (like 1, 2, 3, 4), using values from the array in any order. For example, [100, 4, 200, 1, 3, 2]
contains 1, 2, 3, 4, so the answer is 4. An empty array gives 0. LeetCode asks for an O(n) solution.
The function name longestConsecutive matches LeetCode. Use the link above for the exact statement.
Think first
- Sorting makes runs easy to see. What does it cost?
- Without sorting, how could you quickly check whether
x + 1is in the array? - If every value starts its own walk upwards, how much repeated work is there? Which values should be allowed to start a walk?
Hints
Brute force, and why it fails
Sort the array and scan it, counting runs and skipping repeats: O(n log n), which is a fine answer in practice. Starting a walk from every value with a set is correct but can be O(n²) on one long run.
The key insight
A run is only measured from its first value. Since each value belongs to exactly one run, the total walking is O(n), and the set makes every step O(1).
Dry run
| best | 0 |
|---|
nums = [100, 4, 200, 1, 3, 2]. Put every value in a set so "is v present?" takes one step.
The plan
values = set of all nums
best = 0
for x in values:
if x - 1 is in values:
continue # not the start of a run
length = 1
while x + length is in values:
length = length + 1
best = max(best, length)
return best
Complexity
- Time
O(n)- Space
O(n)
Building the set is O(n). Each value is checked once as a possible start and stepped over at most once inside a walk.
Edge cases
- Empty array: 0.
- Repeats, as in
[1, 2, 0, 1]: the set removes them, and the answer is 3. - Negative numbers work, as in
[-1, -2, -3, 10], which gives 3.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> values = new HashSet<>();
for (int x : nums) {
values.add(x);
}
int best = 0;
for (int x : values) {
if (values.contains(x - 1)) {
continue; // not the start of a run
}
int length = 1;
while (values.contains(x + length)) {
length++; // walk the run upwards
}
best = Math.max(best, length);
}
return best;
}
}C++
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> values(nums.begin(), nums.end());
int best = 0;
for (int x : values) {
if (values.count(x - 1)) {
continue; // not the start of a run
}
int length = 1;
while (values.count(x + length)) {
length++; // walk the run upwards
}
best = max(best, length);
}
return best;
}
};Python
class Solution:
def longestConsecutive(self, nums: list[int]) -> int:
values = set(nums)
best = 0
for x in values:
if x - 1 in values:
continue # not the start of a run
length = 1
while x + length in values:
length += 1 # walk the run upwards
best = max(best, length)
return bestCommon mistakes
- Walking from every value, which is O(n²) on input like 1, 2, 3, ..., n.
- Looping over the original array instead of the set, which repeats work for duplicates.
- Counting repeated values as part of the run after sorting.