DSAHashingFrequencies

Count Pairs with Sum Visualizer

What is Count Pairs with Sum

How many unordered pairs add to k? Keep frequencies of values already seen. For x, every previous k − x forms a valid pair. Then increment freq[x].

  • Count, do not just exist: if 3 appeared twice, a new 7 (k=10) adds two pairs.
  • Order of insert: add after the query so each pair is counted once.
  • Self pairs: two equal values that sum to k are handled naturally by the previous counts.

How this visualizer works

Array 1, 5, 7, -1, 5, k = 6. Pairs are (1,5), (7,-1), (1,5) — answer 3.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def countPairs(arr, k):
2freq, ans = {}, 0
3for x in arr:
4ans += freq.get(k - x, 0)
5freq[x] = freq.get(x,0)+1
6return ans

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def countPairs(arr, k):
2freq, ans = {}, 0
3for x in arr:
4ans += freq.get(k - x, 0)
5freq[x] = freq.get(x,0)+1
6return ans

complexity.md

OperationTime
Each elementO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def countPairs(arr, k):
2 freq, ans = {}, 0
3 for x in arr:
4 ans += freq.get(k - x, 0)
5 freq[x] = freq.get(x, 0) + 1
6 return ans