Longest Consecutive Sequence in an Array
Problem Statement:ā
You are given an array of āNā integers. You need to find the length of the longest sequence which contains the consecutive elements
-
Example:
Example 1:
Input: [100, 200, 1, 3, 2, 4]
Output: 4
Explanation: The longest consecutive subsequence is 1, 2, 3, and 4.
Input: [3, 8, 5, 7, 6]
Output: 4
Explanation: The longest consecutive subsequence is 5, 6, 7, and 8.
ā Solution: HashSet + Sequence Starter Checkā
int longestConsecutive(vector<int>& numbers) {
unordered_set<int> numberSet;
int maxLength = 0;
// Insert all elements into an unordered set
for (int num : numbers) {
numberSet.insert(num);
}
// Check each number: is it the start of a sequence?
for (int num : numberSet) {
if (numberSet.find(num - 1) == numberSet.end()) {
int currentNum = num;
int currentStreak = 1;
// Count length of the current sequence
while (numberSet.find(currentNum + 1) != numberSet.end()) {
currentNum++;
currentStreak++;
}
maxLength = max(maxLength, currentStreak);
}
}
return maxLength;
}
š How It Worksā
- First, insert all elements into an unordered set to allow O(1) lookups.
- Iterate over each number and check if it is the start of a sequence by checking if
num - 1is not in the set. - If it's a starting point, increment
currentNumuntil the sequence breaks, counting the streak. - Track the maximum length found.
š§© Key Logicā
If (num - 1) not in set ā it's a sequence start
Then check for (num + 1), (num + 2), ... and count streak
ā±ļø Time & Space Complexityā
| Metric | Value |
|---|---|
| ā± Time | O(n) |
| š Space | O(n) |
Each number is processed at most once due to set-based sequence checking.
ā ļø Edge Casesā
- Empty array ā return 0
- All numbers same ā return 1
- Single-element array ā return 1
- Already sorted array ā correctly finds full length
š” Other Approachesā
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute Force + Sort | O(n log n) | O(1) | ā Can't handle duplicates easily |
| HashSet (this) | O(n) | O(n) | ā Best and optimal |
š Related Problemsā
š¬