Two Sum — interactive algorithm visualization

Easy · Hash Map · time O(n) · space O(n)

Store each value's index in a map and look up the complement. Trades space for O(n) time.

Example input: nums = [2,7,11,15], target = 9

Step through a verified execution trace - every step shows the real state, the invariant that keeps the algorithm correct, and asks you to predict what happens next.

Jump straight to a moment: initialize · search · store · found

How Two Sum actually works

Two Sum looks like a nested-loop problem - check every pair - but the hash map turns it into a single pass. The trick is to stop asking 'which pair sums to the target?' and start asking, for each number, 'have I already seen the one number that would complete it?' That question is answerable in O(1).

An empty map is a promise

seen = {} will map each value to its index. The promise the loop maintains: by the time nums[i] is examined, every earlier value is in the map. That is what makes 'have I seen the complement?' a complete answer rather than a partial one.

Watch this moment in the trace

Ask for the complement

For nums[i], the only number that helps is target - nums[i] - the complement. One map lookup answers whether it exists among the earlier values. This is the moment the O(n^2) pair-checking collapses into O(n): the map answers in one step what a second loop would answer in n.

Watch this moment in the trace

Record, then move on

If the complement is not there yet, store nums[i] -> i and continue. Storing AFTER the lookup is deliberate: it prevents a number from pairing with itself when target is exactly twice the value.

Watch this moment in the trace

The pair completes

When the lookup hits, the stored index and the current index are the answer - and the earlier index always comes first, because the map only ever holds positions already passed.

Watch this moment in the trace

Common confusions

Why not sort and use two pointers?

Sorting works for 'do such numbers exist?' but this problem wants the ORIGINAL indices, which sorting destroys. Keeping index pairs through a sort costs more bookkeeping than the map costs memory.

Can the same element be used twice?

No - and the store-after-lookup order enforces it structurally. When nums[i] is looked up, the map holds only indices before i, so a value can never find itself.

Solve Two Sum in the editor · All 16 visualizations

Previous: Reverse Linked List · Next: Breadth-First Search