Tensorum
LeetCode 128 · Hashing / Anagram

Longest Consecutive Sequence

LeetCode 128 · Medium · solution, intuition & step-by-step walkthrough

Only expand from run starts (num − 1 not in set).

MediumArrayHash TableUnion-Find
48 msruntime · beats 76%
36.6 MBmemory · beats 30%
1approach
9accepted runs · last 12 Mar 2026

This is how I solved Longest Consecutive Sequence (LeetCode 128), a medium problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.

Approach

  1. 1

    Build a set (removes duplicates, O(1) lookups).

  2. 2

    For each num with no predecessor, walk num+1, num+2, … counting length.

  3. 3

    Track the longest run.

How I solved it

Hash set + run startsPythonO(n) time · O(n) space
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums:
            return 0
        unique_elenents = set(nums) #remove duplicates
        max_length = 1 #single element 
        for num in unique_elenents:
            if num-1 not in unique_elenents:
                length = 1
                while num+1 in unique_elenents:
                    num = num+1
                    length+=1
                max_length=max(max_length,length)
        return max_length
Loading the step-through…

Longest Consecutive Sequence — FAQ

What is the intuition behind Longest Consecutive Sequence?

Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.

How do you solve Longest Consecutive Sequence (LeetCode 128)?

1. Build a set (removes duplicates, O(1) lookups). 2. For each num with no predecessor, walk num+1, num+2, … counting length. 3. Track the longest run.

What is the time and space complexity of Longest Consecutive Sequence?

Time: O(n). Space: O(n). (Accepted approach: Hash set + run starts.)

What are common mistakes in Longest Consecutive Sequence?

Without the 'is it a start?' check the algorithm degrades to O(n²). Empty input returns 0.