Python Algorithms

Two Sum Problem in Python

Find two numbers that add up to a target in a single pass, using a dictionary to remember what you have seen.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • The complement target - value
  • Storing seen values in a dict
  • O(n) time instead of O(n²)
[2, 7, 11, 15], target 9
index 0: 2need 7, not seen yet → seen = {2: 0}
index 1: 7need 2, found at 0 → [0, 1]

Look for the missing partner

The Two Sum problem is a common introduction to hash tables and trading extra memory for faster lookup.

Key points

  1. For each value, the partner you need is target - value.
  2. If the partner is already in seen, you have the answer.
  3. Otherwise store seen[value] = index and continue.

When should you use it?

  • Practice problem solving and data structures.
  • Process data when every algorithm step must be explicit.
  • Prepare for programming exercises, exams, and interviews.

Example code

Run code →
main.py
def two_sum(values, target):
    seen = {}
    for index, value in enumerate(values):
        complement = target - value
        if complement in seen:
            return [seen[complement], index]
        seen[value] = index
    return []

print(two_sum([2, 7, 11, 15], 9))
Get a Run button for this example

Result of running the code

[0, 1]

Code explanation

The dictionary stores values already visited. Looking up the required complement makes the algorithm O(n) time with O(n) extra space.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in the Python compiler →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges