Longest Consecutive Sequence

Find the length of the longest consecutive elements sequence.

Pattern

Hash Set Sequence

This problem follows the Hash Set Sequence pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Add all to a set. For each number with no left neighbor, count the sequence length.

Key Insight

Only start counting from sequence beginnings (numbers with no left neighbor) — this ensures each element is visited at most twice, giving O(n).

Step-by-step

  1. 1Add all numbers to a hash set for O(1) lookup
  2. 2For each number, check if (num - 1) exists in the set
  3. 3If not, this number is the start of a sequence — count forward
  4. 4Track the maximum sequence length found

Pseudocode

numSet = set(nums)
longest = 0
for num in numSet:
    if num - 1 not in numSet:  # start of sequence
        length = 1
        while num + length in numSet:
            length += 1
        longest = max(longest, length)
return longest
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Arrays & Hashing Problems

Master this pattern with YeetCode

Practice Longest Consecutive Sequence and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.

Practice this problem