Longest consecutive sequence
Put everything in a set, then only start counting from a value whose predecessor is absent. That single check is what keeps it O(n): every run is walked exactly once, from its start, so the inner loop across the whole input does n steps in total rather than n per element.
Step through it
What to watch
- Values with a predecessor present are skipped without any work.
- Each run is walked exactly once, from its lowest member.
- The input is never sorted.
Say this out loud
"Set for O(1) membership, then for each value check whether value-1 is in the set. If it is, skip - something else starts that run. If it isn't, walk forward. Every element is visited at most twice, so O(n)."