#1EasyHashmap
Two Sum
Start dumb: try every pair
Two indices whose values sum to target — the honest first idea is the
double loop: for every i, scan every j > i and test the sum. That’s
O(n²), and on LeetCode’s 10⁴ elements it’s fifty million useless
comparisons for one pair.
Find the bottleneck
Watch what the inner loop actually does: given nums[i], it searches
for one specific value. Because the pair must sum to target, the second
number is fully determined the moment you see the first — it must be
target − nums[i]. The brute force spends O(n) hunting for a value it
could have looked up by name.
The optimal shape
- Compute the complement
target − nums[i]. - Look it up in the map — a hit means the pair is complete; return the remembered index and the current one.
- Miss → record
nums[i] → iand move on.
The lookup happens before the insert on every iteration — that ordering is load-bearing (see the trap below). In the player, the map in the state pane grows left to right; the hit lights up both partners.
Watch it think
Run the default, then the traps: the self-pair case (3,2,4 | 6),
duplicates that legitimately pair (3,3 | 6), negatives
(-3,4,90 | 1), and a target no pair can reach (1,2,3 | 7).
Re-traces as you type — comma-separated integers (2–12 of them), a pipe, then the target — e.g. "2,7,11,15 | 9" or the self-pair trap "3,2,4 | 6". Capped at 32 characters so the tiles stay readable.
Step 1 of 5: For every value the partner it needs is fully determined — target minus itself — so the plan is to remember each value's index and let lookups replace searching. Variables: target = 9, seen = {}.
Data
Code
1fun twoSum(nums: IntArray, target: Int): IntArray {2 val seen = HashMap<Int, Int>()3 for (i in nums.indices) {4 val complement = target - nums[i]5 val j = seen[complement]6 if (j != null) return intArrayOf(j, i)7 seen[nums[i]] = i8 }9 return intArrayOf()10}
State
- target
- 9
- seen
- {}
Why this step
For every value the partner it needs is fully determined — target minus itself — so the plan is to remember each value's index and let lookups replace searching.
1 / 5
The same pattern also solves
Recognize the window, and these fall to the same skeleton.
- Two Sum II - Input Array Is Sorted (LC 167) ↗
When the input is sorted, converging two pointers replace the map — O(1) space because sortedness is the lookup table.
- 3Sum (LC 15) ↗
The interviewer's favorite escalation — fix one element, solve Two Sum on the rest.
- 4Sum (LC 18) ↗
Two nested fixes, then the same pair search — the pattern stacks.
- Two Sum III - Data structure design (LC 170) ↗
The streaming pivot — design add/find around the same value→index map.