Two Sum, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 1). Technique: hash map. Solution in Python, explained at every step.

The problem

You get an array of numbers and a target. Exactly one pair of elements adds up to the target: return their indices. The same element can't be used twice.

Example: in [8, 3, 11, 6, 10, 4] with target 13, the answer is [1, 4], because 3 + 10 = 13 (indices count from 0).

The array 8, 3, 11, 6, 10, 4, its indices 0 to 5 above it, and target = 13. The cells holding 3, at index 1, and 10, at index 4, are green and joined by a bracket labelled 3 + 10 = 13. Under it: answer: [1, 4].
The answer is the two indices, not the two values.

Try it yourself first: LeetCode 1 ↗. Then step through the solution below.

Brute force

Try every pair: add each element to every element after it and compare the sum with the target. Six elements make 15 pairs, and n elements make n(n − 1) / 2, so the time is O(n2). No extra memory is needed: O(1) space.

The key insight

For each element x, its partner is not a mystery: it must be exactly target − x. So the question for every element is not "which element pairs with me?" but "have I already seen target − x?"

A hash map answers that in O(1) on average. Walk the array once: first look the partner up in the map, then add the current value with its index. When the second element of the pair arrives, its partner is already in the map.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Two Sum, step by step

Python

def two_sum(nums, target):    seen = {}  # value -> index    for i, x in enumerate(nums):        need = target - x        if need in seen:            return [seen[need], i]        seen[x] = i    return []
All steps as text
  1. The array has 6 elements, and the target is 13. Which two of them add up to 13?
  2. The map seen starts empty. It will hold each value already passed, with its index.
  3. The loop takes the first element: x is 8, at index i = 0. Its partner need is 13 − 8 = 5, and seen has no 5.
  4. Add 8 to seen, with its index 0.
  5. Next, 3 needs 13 − 3 = 10. There is no 10 in seen yet: it comes later in the array.
  6. Add 3 to seen, with its index 1.
  7. Next, 11 needs 13 − 11 = 2, and seen has no 2.
  8. Add 11 to seen, with its index 2.
  9. Next, 6 needs 13 − 6 = 7, and seen has no 7.
  10. Add 6 to seen, with its index 3.
  11. Next, 10 needs 13 − 10 = 3, and 3 is in seen, at index 1.
  12. Return [1, 4]: 3 + 10 = 13. The last element, 4, is never looked at.
  13. One pass: 5 elements looked at, one lookup in seen each. That is O(n) time.
Two Sum, step by step. Last step: One pass: 5 elements looked at, one lookup in seen each. That is O(n) time.

Complexity

ApproachTimeSpace
Brute force: try every pairO(n2)O(1)
Sort with the indices, then two indices from the endsO(n log n)O(n)
Hash map, one pass this pageO(n)O(n)
  • Time: O(n). One pass over the array, and each element does one lookup and at most one insertion in the hash map, both O(1) on average.
  • Space: O(n). In the worst case the pair is found at the last element, so the map holds every element before it.

Note

O(1) is the hash map's average. When many keys collide, a lookup slows down: to O(n) in Python's dict and C++'s unordered_map. Java's HashMap turns a long chain of colliding keys into a balanced tree, which keeps its worst case near O(log n).

Edge cases

  • Two equal values, like [5, 5] with target 10: the first 5 goes into the map at index 0, and the second finds it there: [0, 1]. The lookup comes before the insertion, so an element never pairs with itself.
  • Half the target appears once, like 5 in [5, 2, 8] with target 10: when 5 looks for 5, the map is still empty, so it is not paired with itself; 2 and 8 are: [1, 2].
  • Negative numbers and zero need nothing special: in [-3, 4, 7] with target 4, 7 looks for 4 − 7 = −3 and finds it at index 0: [0, 2].
  • No pair at all: the problem promises one, but if there is none, the loop ends and the function returns an empty list.

Try it: put Two Sum together step by step

The blocks below are steps of Two Sum in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example and on [5, 2, 8] with target 10, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Two Sum together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

What if the array is sorted? Then two indices, one at each end, are enough: if their sum is too small, move the left one right; if too large, move the right one left. That is O(n) time and O(1) space, with no map: Two Sum II (LeetCode 167). Sorting an unsorted array first costs O(n log n), and each value must carry its index through the sort, so the hash map stays the answer for the problem as asked.

The data structure behind it

  • Hash table: how a hash map finds a key in O(1) on average, step by step.
  • Array: elements, indices and why looking through an array is O(n).