128. Longest Consecutive Sequence
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Arrays & Hashing
- Time
- O(n)
- Space
- O(n)
Standard Solution (C++)
SummaryGiven an unsorted array of integers, find the length of the longest run of consecutive integers (e.g., 1, 2, 3, 4) that can be formed from the array's elements, in O(n) time.
Approach
- Insert all numbers into a hash set for O(1) lookup.
- For each number that has no predecessor (i.e.,
n-1is not in the set), treat it as the start of a new sequence and extend forward as far as possible. - Skipping non-starts ensures each element is visited at most twice across all sequences, keeping the total work linear.
- Track and return the maximum length seen across all sequences.
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> numSet(nums.begin(), nums.end());
int best = 0;
for (int n : numSet) {
// Only start a new sequence from its smallest element
if (numSet.find(n - 1) == numSet.end()) {
int length = 1;
while (numSet.count(n + length))
++length;
best = max(best, length);
}
}
return best;
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> uset(nums.begin(), nums.end());
int maxSeqLength=0; // longest consecutive sequence
for(const int& n: uset){
if(!uset.count(n-1)){
int curSeqLength=1;
int curNum=n+1;
while(uset.count(curNum)){
++curNum;
++curSeqLength;
}
maxSeqLength=std::max(maxSeqLength, curSeqLength);
}
}
return maxSeqLength;
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) Time O(n) Space O(n)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.