Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Hash Map / Set High frequency Solution Available Practice Mode

Longest Consecutive Sequence LeetCode Solution

Tags: #Array #Hash Set

Approach Summary

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

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

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

Frequently Asked Questions

What is the optimal time and space complexity for Longest Consecutive Sequence?
The optimal solution for Longest Consecutive Sequence achieves O(n) runtime complexity and requires O(n) auxiliary space. Time Complexity is O(N) where N is the length of the array. Inserting elements into the hash set takes O(N) average time. In the sequence check, inner while loops only execute for numbers that are the first element of a streak. Across the entire array, each element is part of exactly one streak, so inner lookups sum to N total steps. Space Complexity is O(N) to store the distinct elements in the hash set.
How do I identify that Longest Consecutive Sequence requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: Longest consecutive streak; O(n) required. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in Longest Consecutive Sequence?
Essential edge cases to verify include: Empty array — return 0; Single element array — return 1; Duplicates present (e.g. [1, 2, 0, 1]) — hash set naturally deduplicates them without affecting sequence length; Negative numbers and large gaps (e.g. [-5, -4, 100, 200]) — streak starts correctly at -5 with length 2. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Longest Consecutive Sequence?
Longest Consecutive Sequence is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Google, Facebook, Amazon.
Buy me a coffee
Daily Practice
0/0