Longest Consecutive Sequence: Hash and Union-Find Approaches
Last updated on March 15, 2025 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Problem
Given an unsorted integer array nums, find the length of the longest sequence of consecutive numbers (the sequence elements are not required to be consecutive in the original array).
Design and implement an algorithm with time complexity O(n) to solve this problem.
Example
Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive sequence is [1, 2, 3, 4]. Its length is 4.
Solution
The problem requires a time complexity of $O(n)$, so sorting is definitely not an option, since sorting has a complexity of at least $O(nlogn)$.
Below we solve this problem from two perspectives:
1. Hashing
Let's first analyze an obvious brute-force solution: first store all the numbers in a hash set, then iterate with a double loop to check whether they match.
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s;
for(int x:nums) s.insert(x);
int ans=0;
for(int x:s){
int l=1; //表示当前序列长度
int n=x+1; //表示当前的数
while(s.find(n)!=s.end()){
l++;
n++;
}
ans=max(ans,l);
}
return ans;
}However, this time complexity is too high. Upon careful analysis, we can find that the reason is that the outer loop performs many unnecessary enumerations. We can optimize it as follows: each time, check whether the predecessor x-1 of the number x exists. If it exists, then the sequence we are about to enumerate is definitely not the longest one, so we only need to enumerate the numbers that have no predecessor each time.
代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s;
for(int x:nums) s.insert(x);
int ans=0;
for(int x:s){
if(s.find(x-1)==s.end()){
int l=1;
int n=x+1;
while(s.find(n)!=s.end()){
l++;
n++;
}
ans=max(ans,l);
}
}
return ans;
}
};2. Union-Find
Treat consecutive numbers as one set. Then, when scanning a number, we only need to Union it with its next number (if it exists) into one set. At the same time, update the element count of this set, and also update the current longest record.
代码
class Solution {
public:
unordered_map<int, int> father;
unordered_map<int, int> cnt;
int findFather(int x) {
if (x == father[x]) return x;
return father[x] = findFather(father[x]);
}
void Union(int x, int y) {
int fx = findFather(x);
int fy = findFather(y);
if (fx != fy) {
father[fx]=fy;
cnt[fy]+=cnt[fx];
}
}
int longestConsecutive(vector<int>& nums) {
for(int x:nums){
father[x]=x;
cnt[x]=1;
}
int ans=0;
for(int x:nums){
if(father.find(x+1)!=father.end()){
Union(x,x+1);
ans=max(ans,cnt[findFather(x)]);
}
}
return ans;
}
};Here a cnt is used to record the number of elements in a set, because if we computed it at the end instead, the time complexity would be exceeded.