The trick: only start counting from the beginning of a sequence. A number is the start of a sequence if is not in the set.
If exists, then 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: .