Longest Consecutive Sequence

Medium

Topics
ArrayHash TableUnion Find

Given an unsorted array nums, return the length of the longest run of consecutive integers. You must do it in O(n) time.

Example 1

1000412002133425
the longest run, in any order
The run does not have to be contiguous in the array — only consecutive in value. Shaded here: 1…4, length 4.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [100,4,200,1,3,2]
Output: 4
Explanation: The run [1,2,3,4] has length 4.

Example 2

00317223548546670819
the longest run, in any order
Input:  nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sorting would be O(n log n). To hit O(n), drop everything into a hash set for O(1) membership.

The trick is to only start counting a run from its smallest element — a number x where x-1 is not in the set. That guarantees each element is walked at most once.

Approach

  1. Put all numbers in a set.
  2. For each number that has no predecessor (x-1 not in set), walk x, x+1, x+2, ... counting the run.
  3. Track the longest run seen.

Walkthrough

nums = [100,4,200,1,3,2]  set={1,2,3,4,100,200}
start at 1 (0 not in set): 1,2,3,4 -> len 4
start at 100: 100 -> len 1
start at 200: 200 -> len 1
answer 4

Complexity

  • Time — O(n): each number is visited once as part of exactly one run.
  • Space — O(n): the hash set holds all numbers.

Common Pitfalls

  • Only start a walk at run-starts, or you re-scan runs and degrade to O(n²).

Full Solution — all languages

class Solution:
    def longestConsecutive(self, nums):
        s = set(nums)
        best = 0
        for x in s:
            if x - 1 not in s:
                y = x
                while y + 1 in s:
                    y += 1
                best = max(best, y - x + 1)
        return best
SensAI
Beta
Tap the mic to stop voice mode