Back to Problem
Official 330 views

Editorial: Longest Consecutive Sequence

by admin ·

10

1 Intuition

Only start counting from numbers that begin a run.

2 Approach

Put everything in a set. For each x whose predecessor is missing, walk upward while the next value exists.

3 Complexity Analysis

Time O(n) — each value is visited a constant number of times. Space O(n).

4 Solution Code

class Solution:
    def longestConsecutive(self, nums: list[int]) -> int:
        s, best = set(nums), 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

5 Code Walkthrough

The reference solution below implements the approach step by step.