Longest Consecutive Sequence
Medium
Topics
Given an unsorted array nums, return the length of the longest run of consecutive integers. You must do it in O(n) time.
Example 1
the longest run, in any order
The run does not have to be contiguous in the array — only consecutive in value. Shaded here: 1…4, length 4.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The run [1,2,3,4] has length 4.
Example 2
the longest run, in any order
Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9
Constraints
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Sorting would be O(n log n). To hit O(n), drop everything into a hash set for O(1) membership.
The trick is to only start counting a run from its smallest element — a number x where x-1 is not in the set. That guarantees each element is walked at most once.
Approach
- Put all numbers in a set.
- For each number that has no predecessor (
x-1not in set), walkx, x+1, x+2, ...counting the run. - Track the longest run seen.
Walkthrough
nums = [100,4,200,1,3,2] set={1,2,3,4,100,200}
start at 1 (0 not in set): 1,2,3,4 -> len 4
start at 100: 100 -> len 1
start at 200: 200 -> len 1
answer 4Complexity
- Time — O(n): each number is visited once as part of exactly one run.
- Space — O(n): the hash set holds all numbers.
Common Pitfalls
- Only start a walk at run-starts, or you re-scan runs and degrade to O(n²).
Full Solution — all languages
class Solution:
def longestConsecutive(self, nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s:
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return bestimport java.util.*;
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) s.add(x);
int best = 0;
for (int x : s) {
if (!s.contains(x - 1)) {
int y = x;
while (s.contains(y + 1)) y++;
best = Math.max(best, y - x + 1);
}
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int best = 0;
for (int x : s) {
if (!s.count(x - 1)) {
int y = x;
while (s.count(y + 1)) y++;
best = max(best, y - x + 1);
}
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var longestConsecutive = function(nums) {
const s = new Set(nums);
let best = 0;
for (const x of s) {
if (!s.has(x - 1)) {
let y = x;
while (s.has(y + 1)) y++;
best = Math.max(best, y - x + 1);
}
}
return best;
};