DSAHashingComplement

Two Sum Visualizer

What is Two Sum

For each number x ask whether target − x was already stored. The hash map remembers value → index, so the complement check is one probe — not a second loop.

  • Complement: the partner of x is uniquely target − x.
  • Store after the check: that avoids pairing an element with itself.
  • First hit wins: as soon as the complement exists, you have a valid index pair.

How this visualizer works

Input 2, 7, 11, 15 with target 9. 2 is stored, then 7 finds complement 2 and returns [0, 1].

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 twoSum(arr, target):
2idx = {}
3for i, x in enumerate(arr):
4need = target - x
5if need in idx:
6return [idx[need], i]
7idx[x] = i
8return []

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def twoSum(arr, target):
2idx = {}
3for i, x in enumerate(arr):
4need = target - x
5if need in idx:
6return [idx[need], i]
7idx[x] = i
8return []

complexity.md

OperationTime
Complement lookupO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def twoSum(arr, target):
2 idx = {}
3 for i, x in enumerate(arr):
4 need = target - x
5 if need in idx:
6 return [idx[need], i]
7 idx[x] = i
8 return []