Array / HashSet•Pattern: HashSet•Medium

Longest consecutive sequence

Problem Intuition & Objective

Find the length of the longest consecutive integers sequence in O(n).

Time ComplexityO(n)
Optimal
Space ComplexityO(n)
Memory Bounds
Optimal Algorithmic Approach

HashSet: skip non-sequence-starts to ensure each element is visited at most twice total.

Core Invariants & Edge Cases

  • Insert all numbers into a HashSet
  • Only start counting from a number n where n-1 is NOT in the set
  • Extend the streak by checking n+1, n+2, … in the set
Previous ProblemSubarray sum equals KNext Problem Detect and find the start of a cycle in a linked list

System Design & Architecture Roadmap

Coding interviews are only 50% of the bar. Master High-Level Design, distributed systems, and Object-Oriented LLD.