PythonMastery
Python programs · Useful programs · intermediate

Two Sum problem in Python

Find two numbers in a list that add up to a target and return their positions, in one pass with a dictionary instead of two nested loops.

Two Sum is a classic interview problem: given a list of numbers and a target, find the positions of two different numbers that add up to the target.

The program

python
def two_sum(nums, target):
    seen = {}  # number -> its position in the list
    for i, n in enumerate(nums):
        needed = target - n
        if needed in seen:
            return seen[needed], i
        seen[n] = i
    return None


print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 2, 4], 6))
print(two_sum([3, 3], 6))
print(two_sum([-4, 10, 8, 1], 4))
print(two_sum([1, 2, 3], 100))
output
(0, 1)
(1, 2)
(0, 1)
(0, 2)
None

How it works

Why not two loops?

The direct way checks every pair:

python
def two_sum_slow(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return i, j
    return None


print(two_sum_slow([2, 7, 11, 15], 9))
output
(0, 1)

It gives the same answers, but for a list of n numbers it can check about n × n / 2 pairs. For 100,000 numbers that is about 5 billion checks. The dictionary version goes through the list once.

Learn the idea: Dictionaries, Loops: for, while, and the Pythonic Patterns