Step by step · Python and C++

Two Sum with a hash map, visualized

Two Sum (LeetCode 1) asks for two positions whose values add up to a target. Checking every pair is O(n²); remembering what you have already seen makes it O(n).

How it works
nums = [2, 7, 11, 15, 3]
target = 18
seen = {}
answer = None

for i in range(len(nums)):
    complement = target - nums[i]
    if complement in seen:
        answer = (seen[complement], i)
        break
    seen[nums[i]] = i

print(answer)

How Two Sum works

Walk the array once. For each value, compute complement = target − nums[i]. If the complement is already in the map, its stored index and i are the answer. Otherwise store nums[i] → i and move on. Checking before storing is what stops an element from pairing with itself.

The Python example looks for 18 in [2, 7, 11, 15, 3]. At index 2 the complement of 11 is 7, which was stored at index 1, so the answer is (1, 2).

What to watch for when it runs

  1. The map is drawn as a table that gains one row per step.
  2. The complement lookup is a single step each time — there is no inner loop.
  3. The run stops as soon as the pair is found, without reaching the rest of the array.

Time and space complexity

Time
O(n)
Space
O(n)

Hash lookups are O(1) on average. The brute-force double loop needs no extra memory but is O(n²).

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.