Skip to content

Longest Consecutive Sequence

MediumLeetCode #128Time O(n)Space O(n)

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)

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 best
  • Time: O(n) — building the set is O(n), and the inner while loop runs only from run starts, so each number is stepped over once in total.
  • Space: O(n) — the set holds up to n distinct values.
  • 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 best at 0 covers it with no special case.

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].

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.