Data Structures19 sections · 729 units
Open in Course

Longest Consecutive - Algorithm

Two-phase approach

Phase 1: Add all numbers to a hash set.

Phase 2: For each number xx in the set:

  • If x1x - 1 is not in the set, xx is a sequence start
  • Count consecutive numbers: x,x+1,x+2,...x, x+1, x+2, ... until not found
  • Update the maximum length

Why is this O(n)O(n)?

Each number is the start of exactly one sequence. The inner counting loop visits each number at most once across all iterations. Time: O(n)O(n). Space: O(n)O(n).