Skip to main content
Medium Hash Map / Set High frequency

Longest Consecutive Sequence

Open on LeetCode

Approach Summary

Put all numbers in a set. For each number that has no predecessor (n-1 not in set), count consecutive streak forward.

Full Solution & Approach

The brute force checks each element and extends a run while consecutive values exist — but doing that naively for every element is O(n²). The insight: only start counting a run at the beginning of a run. Convert the array to a set for O(1) membership tests. For each number n, if n - 1 is not in the set, then n is the start of a consecutive run — count how many steps you can take while n + length is in the set. Every number belongs to exactly one run, and only the first element of each run triggers a scan, so the total work across all runs is O(n): each element is visited once as part of one run's scan plus once in the outer loop. This avoids the sorting-based O(n log n) solution entirely.

Each element is examined a constant number of times — once in the outer loop and at most once inside a run scan — so O(n) time. A set of n elements gives O(n) space.

Solution Code

Solution

def longest_consecutive(nums: list[int]) -> int:
    num_set = set(nums)
    best = 0
    for n in num_set:
        if n - 1 not in num_set:
            length = 1
            while n + length in num_set:
                length += 1
            best = max(best, length)
    return best

Edge Cases to Watch

  • Empty array — return 0
  • All elements identical — the run has length 1
  • Negative numbers — runs work on any integers
  • The full range present, e.g. 1..100000 — each element scanned once by the run logic

How to Recognize This Pattern

  • Longest consecutive streak
  • O(n) required

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Hash Set

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee