Name the partner, then count
transcript
Two fares must make a total. An interviewer asks how many pairs there are. Checking every pair is slow. One pass is enough. Here is how.
First, name the partner of x. For a total, it is total minus x. For a gap, it is x plus d.
Fares two, three, three, two, three. Total five. The first two finds no three. Count zero. Each three finds one earlier two. The next two finds two threes. Four. The last three finds two twos. Six.
Look up the partner first. Then store the fare. So no fare pairs with itself.
The map holds counts, not positions. Each count is how many came before. One lookup adds every pair ending here.
Counts grow fast. A hundred thousand equal fares make five billion pairs. Use sixty-four bits.
Name the partner as one exact key. Look up first, then store the item. Count in sixty-four bits. Full breakdown in the lecture.