#128

Longest Consecutive Sequence

Medium HashSet, start only at run starts

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the length of the longest run of consecutive integers (like 4, 5, 6, 7) found in an unsorted array, in O(n).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest run like 4, 5, 6, 7 hidden in an unsorted array, in O(n).

Why this works: only start counting from x when x - 1 is missing (x starts a run). Each number is then counted once.

Example: [100, 4, 200, 1, 3, 2]

1 starts a run: 1, 2, 3, 4 → length 4100 and 200: length 1 each

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Counting upward from every number, which makes it O(n²) on one long run.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Hashing
🎬 Episodes 37–39: video coming soon