Longest Consecutive Sequence (LeetCode 128): Solution and Explanation

Medium
Array
Hash Table
Union Find

Given an unsorted array of integers, return the length of the longest run of consecutive values, such as 1, 2, 3, 4, that all appear in the array. The values do not need to be adjacent in the input, and the solution should run in linear time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

If you sort the array, consecutive values line up next to each other and one scan finds the longest run. That is O(n log n), and the problem asks for O(n), so sorting is out. Without sorting, the natural tool for "is the value x + 1 present?" is a hash set, which answers in constant time. So a first idea is: for every number, keep checking n + 1, n + 2 and so on in the set and count how far you get.

That idea has a hidden cost. For the run 1, 2, 3, 4, it counts 4 steps from 1, then 3 steps from 2, then 2 from 3 and 1 from 4. A single long run of length n would cost O(n²) work, because every element re-walks the rest of its run. The fix is to only count from the beginning of a run. A number n starts a run exactly when n - 1 is not in the set. Every other number is in the middle of some run and will be covered when you count from that run's start.

With that rule, each run is walked once from its start, so the total number of set lookups across all runs is proportional to the number of distinct values. The loop over elements does one extra lookup each to test n - 1, which is also linear. The answer is the longest length you counted.

Approach: Hash set and sequence starts

  1. Build numSet = set(nums) for constant time membership checks, and set longest = 0.
  2. Loop over each n in nums.
  3. If n - 1 is in numSet, skip n; it is not the start of a run.
  4. Otherwise set length = 0 and keep incrementing it while n + length is in numSet.
  5. Update longest = max(length, longest).
  6. Return longest after the loop.

Step-by-step example

nums = [100, 4, 200, 1, 3, 2]
  1. numSet = {100, 4, 200, 1, 3, 2}.
  2. n = 100: 99 is not in the set, so 100 starts a run. 101 is missing, so length = 1 and longest = 1.
  3. n = 4: 3 is in the set, so skip.
  4. n = 200: 199 is missing, so it starts a run of length 1. longest stays 1.
  5. n = 1: 0 is missing, so count 1, 2, 3 and 4, all present; 5 is missing. length = 4 and longest = 4.
  6. n = 3 and n = 2 both have their predecessor in the set and are skipped. Return 4.

Code: Python, Java, C++

1class Solution:
2    def longestConsecutive(self, nums: List[int]) -> int:
3        numSet = set(nums)
4        longest = 0
5
6        for n in nums:
7            # Check if it's the start of a sequence
8            if (n - 1) not in numSet:
9                length = 0
10                while (n + length) in numSet:
11                    length += 1
12                longest = max(length, longest)
13        
14        return longest

Time and space complexity

Time

O(n)

Building the set is O(n). Each element does one lookup for n - 1, and the inner while loop only runs from run starts, so across all distinct starts it advances through each value once. One caveat: because the outer loop walks nums rather than numSet, a run start that appears many times is recounted each time; looping over the set removes that edge case.

Space

O(n)

The hash set stores up to n distinct values.

Other approaches

Sort and scan (time O(n log n), space O(1) to O(n))

Sort the array, then walk it once, extending the current run when the next value is exactly one larger, ignoring duplicates, and resetting otherwise. It is simple and uses little memory but violates the linear time requirement.

Union-find (time O(n α(n)), space O(n))

Treat each value as a node and union it with n + 1 when present. The largest component size is the answer. It is near linear but much more code than the set approach.

Common mistakes

  • Counting forward from every number instead of only from run starts. That turns the algorithm quadratic on inputs like a long sorted range.
  • Iterating over nums when it contains many copies of a run start. Each copy restarts the count; iterating over numSet avoids the repeated work.
  • Returning 1 for an empty array. With no elements there is no sequence, so the answer is 0, which the longest = 0 initialization handles.
  • Sorting and then forgetting to skip duplicates, so [1, 2, 2, 3] incorrectly resets the run at the second 2.

Frequently asked questions

How is Longest Consecutive Sequence O(n) when there is a nested loop?

The inner while loop only runs for numbers whose predecessor is missing, and it walks each run exactly once. Summed over all runs, the inner loop does at most n steps in total, so the whole algorithm stays linear.

Why check whether n - 1 is in the set?

It identifies the smallest element of a run. Counting only from there guarantees each run is measured once instead of once per element.

Can I just sort the array?

Sorting gives a correct O(n log n) solution and is fine when the linear requirement is relaxed. Remember to skip duplicates while scanning.

Do duplicates break the hash set approach?

No. The set stores each value once, so duplicates do not change any run length. They can only cause repeated counting if you iterate over the original array.