Longest Consecutive Sequence
The problem
Section titled “The problem”You get an unsorted integer array. Find the length of the longest sequence of values that follow each other by exactly 1 (like 1, 2, 3, 4). They do not need to be next to each other in the array. You must run in O(n) time.
nums = [100, 4, 200, 1, 3, 2] -> 4 (the run 1, 2, 3, 4)Key insight
Section titled “Key insight”Sorting makes this easy but costs O(n log n), which the problem forbids. Instead, put
every number in a hash set so “is x present?” is O(1).
Now the trap: if you extend a run from every number, you re-walk the same run many
times and drift to O(n²). The fix is to only start counting at a run’s first number.
A number x is a start exactly when x - 1 is not in the set. From each start, walk
x + 1, x + 2, … while they are in the set. Every number is visited at most twice
overall: once by the outer loop, once by the run that contains it.
Show solutionHide solution
def longest_consecutive(nums: list[int]) -> int: values = set(nums) best = 0 for num in values: if num - 1 in values: # not the start of a run; skip it continue end = num while end + 1 in values: end += 1 best = max(best, end - num + 1) return bestexport function longestConsecutive(nums: number[]): number { const values = new Set(nums); let best = 0; for (const num of values) { if (values.has(num - 1)) continue; // not the start of a run; skip it let end = num; while (values.has(end + 1)) end++; best = Math.max(best, end - num + 1); } return best;}import java.util.HashSet;import java.util.Set;
class Solution { public int longestConsecutive(int[] nums) { Set<Integer> values = new HashSet<>(); for (int num : nums) values.add(num);
int best = 0; for (int num : values) { if (values.contains(num - 1)) continue; // not the start of a run; skip it int end = num; while (values.contains(end + 1)) end++; best = Math.max(best, end - num + 1); } return best; }}Complexity
Section titled “Complexity”- Time: O(n) — building the set is O(n), and the inner
whileloop runs only from run starts, so each number is stepped over once in total. - Space: O(n) — the set holds up to
ndistinct values.
Watch out for
Section titled “Watch out for”- Don’t drop the “is this a start?” check. Without it the code still returns correct
answers but is O(n²) on an input like
[1, 2, ..., n]. This is the usual reason a correct-looking answer fails the follow-up. - Iterate the set, not the array. Duplicates in the array would repeat work. Looping over the set means each distinct value is handled once.
- Empty array returns 0. Starting
bestat 0 covers it with no special case.
Variations
Section titled “Variations”Longest Continuous Increasing Subsequence (LeetCode 674)
Section titled “Longest Continuous Increasing Subsequence (LeetCode 674)”Longest run of strictly increasing values that are adjacent in the array. The
trick: no hash set needed. One pass, resetting a counter whenever
nums[i] <= nums[i - 1].
Summary Ranges (LeetCode 228)
Section titled “Summary Ranges (LeetCode 228)”Given a sorted array of unique integers, output the ranges of consecutive values like
"0->2". The trick: a single pass that extends the current range while the next
number is the previous plus 1, and closes it otherwise.
Binary Tree Longest Consecutive Sequence (LeetCode 298, premium)
Section titled “Binary Tree Longest Consecutive Sequence (LeetCode 298, premium)”Longest downward path where each node is its parent plus 1. The trick: DFS passing down the current run length; extend it if the child equals parent + 1, else reset to 1.