Two Sum
Medium · 60 XPGiven 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.
[0, 1] [1, 2] []
Keep a dict of value→index as you go. For each number, check whether target - number is already in it.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 2, 4], 6))
print(two_sum([1, 2, 3], 99))
Run your code to check it…
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
- [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].
- [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].
- [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.