Longest Consecutive Sequence
Medium · Arrays & hashing
Jump to codeFind the length of the longest run of consecutive integer values present in an unsorted array. Values in the run need not occupy adjacent positions.
Examples
Example 1
nums = [100,4,200,1,3,2]
Output: 4
Example 2
nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Constraints
- 0 <= nums.length <= 1000
- -10^9 <= nums[i] <= 10^9
Need a hint?
Start counting only at the smallest value of a run.
Asked in real interviews
Candidates reported versions of Longest Consecutive Sequence from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Insert all values into a set. For each unique x, skip it if x − 1 exists. Otherwise count x, x + 1, and so on until the run ends. Each value belongs to just one counted run; duplicates do not extend it.
Complexity
O(n) expected time and O(n) space.
Python reference solution
def longestConsecutive(nums):
values = set(nums)
best = 0
for value in values:
if value - 1 in values:
continue
end = value
while end in values:
end += 1
best = max(best, end - value)
return best
JavaScript solution
function longestConsecutive(nums) {
const values = new Set(nums);
let best = 0;
for (const value of values) {
if (values.has(value - 1)) continue;
let end = value;
while (values.has(end)) end++;
best = Math.max(best, end - value);
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int longestConsecutive(int[] nums) {
Set<Long> values = new HashSet<>();
for (int value : nums) values.add((long)value);
int best = 0;
for (long value : values) {
if (values.contains(value - 1)) continue;
long end = value;
while (values.contains(end)) end++;
best = Math.max(best, (int)(end - value));
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestConsecutive(vector<int> &nums) {
unordered_set<long long> values(nums.begin(), nums.end());
int best = 0;
for (long long value : values) {
if (values.count(value - 1)) continue;
long long end = value;
while (values.count(end)) end++;
best = max(best, (int)(end - value));
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 10 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
100,
4,
200,
1,
3,
2
]
]4
[
[
0,
3,
7,
2,
5,
8,
4,
6,
0,
1
]
]9
[ [] ]
0
[
[
5
]
]1
[
[
1,
2,
2,
3
]
]3
Drafts are saved per language in this browser when storage is available.