28 / 75
M

Longest Consecutive Sequence

#28
arrayhash-tableunion-find

Use HashSet to find sequence starts (no n-1) and count consecutive numbers in O(n).

Example:

Input:[100,4,200,1,3,2]
Output:4 (sequence: [1,2,3,4])

Common Mistakes:

  • Sorting first (O(n log n) - violates O(n) requirement)
  • Not checking if number is sequence start (results in O(n²))
  • Using HashMap when HashSet suffices
  • Not handling duplicates properly

Notes:

Key insight: only start counting from sequence beginnings. Each number visited at most twice. Time O(n), Space O(n).

28/75
Longest Consecutive Sequence