Longest Consecutive Sequence
Difficulty: Medium · Pattern: Hashing · LeetCode #128
Given an unsorted integer array nums, return the length of the longest run of consecutive integers (like 3, 4, 5, 6) that can be formed from its values. The values don't need to be adjacent in the array. Aim for O(n) time.
Example
text
nums = [10, 4, 20, 1, 3, 2] → 4 (1, 2, 3, 4)
nums = [0, -1, 5, 6, 7, 8, 9, 1] → 5 (5, 6, 7, 8, 9)Hints
- Sorting gives O(n log n). For O(n), put all values in a set.
- A value x starts a run only if x − 1 is not in the set.
- From each start, count upward while x + 1, x + 2, … are present.
Approach
Put everything in a hash set. For each value x where x − 1 is not present, x is the beginning of a run: walk x+1, x+2, … while they exist and record the length.
Why it's O(n): each value is visited by the inner walk at most once, because only the start of its run launches a walk. Iterate over the set rather than the array to skip duplicates.
Complexity
Time: O(n). Each element is part of exactly one inner walk. Space: O(n).
Python solution
def longestConsecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x starts a run
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return bestJavaScript solution
function longestConsecutive(nums) {
const s = new Set(nums);
let best = 0;
for (const x of s) {
if (!s.has(x - 1)) {
let y = x;
while (s.has(y + 1)) y++;
best = Math.max(best, y - x + 1);
}
}
return best;
}