6/40
Part 1 of 7 · Sets and seen-setsLearn and do

A list as the seen-set is still O(n²)

There's a third version that trips people up. It's the same loop with seen = [] and seen.append(item). It reads like the seen-set version, but item in seen on a list is a scan. So it's every-pair in disguise.

On lists of distinct strings, no duplicate, best of several runs:

nPairs comparedEvery pairList as seenSeen-set
1,000499,50010.1 ms2.8 ms0.029 ms
2,0001,999,00041.7 ms9.8 ms0.071 ms
4,0007,998,000178.2 ms42.1 ms0.136 ms
8,00031,996,000753.5 ms178.4 ms0.305 ms

Double n, and the every-pair and list times grow about four times. That's O(n²).

The seen-set grows about two times. That's O(n). At 8,000 items the seen-set is about 2,500 times faster than comparing every pair, and the gap keeps widening.

You can see why by counting what each version asks of the items. Give 2,000 distinct objects an __eq__ that counts its calls. The list as seen called it 1,999,000 times. The seen-set called it 0 times.

A set compares two keys with == only when their hashes match. These objects hash distinct integers, so no two hashes ever matched.

In the editor, finish unique_in_order(items): each item's first occurrence, in the order they first appear, so [3, 1, 3, 2, 1] gives [3, 1, 2]. Check each item against seen, not against out.