Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Two Sum

Medium · 60 XP

Given a list and a target, return the indices of the two numbers summing to it: in one pass, not nested loops. Print the result for three cases.

Target output
[0, 1]
[1, 2]
[]
Blank · autosaved
PYtwo-sum.py
Run your code to check it…
Guide

How to approach Two Sum

The slow answer checks every pair with two nested loops. The fast answer flips the question: for each number n, you need target - n. If you have already seen that value, you have your pair.

Keep a dictionary from each value seen so far to its index. For each new number, look up its complement first, and only then store the number itself. A dict lookup is constant time, so the whole list is processed in a single pass.

Worked through on this data

  1. [2, 7, 11, 15], target 9: at index 0 the complement 7 is not stored yet, so store 2 → 0. At index 1 the complement of 7 is 2, found at 0: [0, 1].
  2. [3, 2, 4], target 6: store 3 → 0 (its complement 3 is not stored yet). Store 2 → 1. At index 2 the complement of 4 is 2, found at 1: [1, 2].
  3. [1, 2, 3], target 99: no complement is ever found, so the function returns []: the third line.

Common mistakes

  • Storing the number before checking it pairs an element with itself: for [3, 2, 4] and target 6, the 3 would find itself and return [0, 0].
  • Returning the values instead of their indices.
  • Sorting first to use two pointers loses the original indices unless you carry them along.

Time and space

One pass with O(1) dict lookups: O(n) time and O(n) space. The nested-loop version is O(n²) time and O(1) space; trading memory for speed like this is the most common optimisation there is.

Where this shows up

Using a dict as a "seen" index turns slow searches into lookups everywhere: matching payments to invoices, finding duplicate records, joining two datasets on a key.

Take it further

Return every distinct pair of values that sums to the target, not just the first, without listing any pair twice.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path