Leetcode 128. Longest Consecutive Sequence
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time complexity.
nums
contain duplicate elements?nums
?nums
is an empty array?nums
can contain both positive and negative integers.To achieve the O(n)
time complexity:
O(1)
average-time complexity checks for the presence of elements.element-1
does not exist in the set.element + k
) in the set.Here’s the C++ code that implements this strategy:
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
unordered_set<int> numSet(nums.begin(), nums.end());
int longestStreak = 0;
for (int num : nums) {
// Check if it's the start of a sequence
if (!numSet.count(num - 1)) {
int currentNum = num;
int currentStreak = 1;
// Check the length of the current streak
while (numSet.count(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longestStreak = max(longestStreak, currentStreak);
}
}
return longestStreak;
}
};
O(n)
O(n)
time.n
times total across all iterations because each element is checked only once.O(n)
O(n)
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?