Has this value appeared before?
transcript
A payment id arrives. Has it appeared before? A set answers in one step. Retries repeat ids all the time. Charging twice is not allowed.
Read fourteen. The set is empty, so add it. Nine and twenty-one are new. Add both. Fourteen again. It is already in the set. That is the first repeat, at position three. The later ids are never read. Each id was read exactly once. The set grew as we read.
Check the set first. In the set? It appeared before. Stop. Not in it? Add it, and read on. The order of these steps matters. Check before you add. Add first, and every id looks repeated.
A list scan reads every earlier id. A set looks in one place. So the pass is n steps, not n squared. Memory pays for the speed. The set holds every id seen. A million ids is no problem.
Check first. Then add. Full breakdown in the lecture.