SDE & MLE Prep

128. Longest Consecutive Sequence

Problem

Given an unsorted integer array nums, return the length of the longest run of consecutive integers (like 1, 2, 3, 4) whose values all appear in nums. The values don't need to be adjacent in the array.

Example: [100,4,200,1,3,2] → 4 (the run 1, 2, 3, 4)

Constraints: n ≤ 10⁵; must run in O(n).

Put everything in a set. Only start counting from numbers that begin a run (x - 1 not in set), then walk x+1, x+2, …. Each number is visited at most twice → O(n).

set {100, 4, 200, 1, 3, 2}
1   (0 missing -> start)  1,2,3,4  -> length 4
100 (99 missing -> start) 100      -> length 1
2   (1 present -> skip, not a start)

Complexity: O(n) time, O(n) space.

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        s = set(nums)
        best = 0
        for x in s:
            if x - 1 not in s:          # x starts a run
                y = x
                while y + 1 in s:
                    y += 1
                best = max(best, y - x + 1)
        return best