Predict the output
What does this print?
from collections import Counter
vals, k = [1, 5, 3, 3, 7], 2
seen: Counter[int] = Counter()
total = 0
for v in vals:
total += seen[v - k] + seen[v + k]
seen[v] += 1
print(total)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 5
Right: 1-3 twice, 5-3 twice and 5-7.
Looking only backwards in the counter is what turns the O(n²) double loop into one pass without double counting.
Why not the others?
- B 3. Both 3s pair with 1 and with 5.
- C 10. Only earlier values are counted, so each pair counts once.