Longest Consecutive Sequence
Difficulty: Medium
Given an unsorted list of integers, find the length of the longest run of consecutive values (like 3, 4, 5, 6) that all appear in the list. They don't need to sit next to each other in the list.
Your solution must run in O(n) time. Sorting takes longer, so it's a fair first attempt but not the intended answer.
Examples
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
The numbers 1, 2, 3, 4 are all present and form a run of consecutive values - the longest one available.
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
0 through 8 are all present (0 shows up twice, which doesn't extend the run), giving a run of length 9.
Input: nums = []
Output: 0
Constraints
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
Approach
A first idea is to sort the list. Consecutive values then sit next to each other, so one pass counting streaks gives the answer. It's correct, but sorting costs more than the required O(n).
The faster solution puts every number in a hash set for instant lookups. Then it only counts a sequence from numbers that start one, meaning "number minus 1" isn't in the set. Every other number is counted as part of a run from its true start. So each number is counted only once, even though there's a loop inside the main loop.
Solutions
Brute Force - Sort and Scan
Remove duplicates and sort. Then walk through once, tracking the current streak of consecutive values and the longest streak seen.
function longestConsecutive(nums) {
if (nums.length === 0) return 0;
const sorted = [...new Set(nums)].sort((a, b) => a - b);
let longest = 1;
let current = 1;
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] === sorted[i - 1] + 1) {
current++;
} else {
current = 1;
}
longest = Math.max(longest, current);
}
return longest;
}Time: O(n log n) · Space: O(n)
Optimal - Hash Set, Start From Sequence Beginnings
Put every number in a hash set. For each number that starts a sequence (one less isn't in the set), count forward while the next value is in the set to get that sequence's length.
function longestConsecutive(nums) {
const numSet = new Set(nums);
let longest = 0;
for (const num of numSet) {
// Only start counting from the beginning of a sequence
if (!numSet.has(num - 1)) {
let length = 1;
while (numSet.has(num + length)) {
length++;
}
longest = Math.max(longest, length);
}
}
return longest;
}Time: O(n) · Space: O(n)