Find length of the longest sequence of consecutive integers in O(N) time.
Problem Statement
Examples
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
Explanation: The longest sequence of consecutive integers is length 9.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
By inserting all numbers into a hash set, we can check for consecutive neighbors in O(1). We only begin expanding a sequence if num - 1 does not exist in the set. This ensures every element is traversed at most twice, resulting in linear O(N) time.
Step-by-Step Approach
- Store all elements in
set = new Set(nums). - Iterate through each
numin the set. - If
!set.has(num - 1), thisnumis the beginning of a sequence. - Count consecutive elements
currentNum + 1while present in the set. - Update
longestStreak = Math.max(longestStreak, currentStreak). - Return
longestStreak.
Optimal Implementation (JavaScript)
function longestConsecutive(nums) {
const set = new Set(nums);
let longestStreak = 0;
for (let num of set) {
if (!set.has(num - 1)) {
let currentNum = num;
let currentStreak = 1;
while (set.has(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty array: returns 0.
- Array of duplicate elements: returns 1.
- Disjoint numbers: returns 1.