Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Stand at each value and look back

At a reunion, everyone shakes hands with each old classmate from their year. How many handshakes? One way to count: as each person arrives, they shake hands with everyone from their year who's already there.

Counting equal pairs works the same way. Walk the list, and at each value ask: how many copies of this value came before me? Each of them makes a pair with this one. A map of counts so far answers that in one lookup.

At each value: count the earlier copies: that's how many new pairs.
Pairs in [2, 2, 5, 2]
2
0
2
1
5
2
2
3
j

No 2s before. pairs = 0, then seen = {2: 1}.

Move 1 of 4

Ask first, then add yourself

Order matters. First add the number of earlier copies to the answer. Then add 1 to this value's count, so that later copies can pair with this one.

Do it the other way round and every value pairs with itself. And use a 64-bit number for the answer: a million equal values make about 500 billion pairs.

Add yourself after asking: or you pair with yourself.
In code
seen = {}
pairs = 0
for x in nums:
    pairs += seen.get(x, 0)
    seen[x] = seen.get(x, 0) + 1
return pairs