Data Structures19 sections · 729 units
Open in Course

Longest Consecutive - The Idea

Start from sequence beginning

The trick: only start counting from the beginning of a sequence. A number xx is the start of a sequence if x1x - 1 is not in the set.

If x1x - 1 exists, then xx is in the middle of some sequence, and you'll count it when you start from the actual beginning.

This guarantees each element is visited at most twice (once in the set check, once in the counting loop). Total: O(n)O(n).