Problem
Given nums = [2, 7, 11, 15] and target = 9, return [0, 1] because nums[0] + nums[1] == 9.
Each input has exactly one solution; you may not use the same element twice.
Naive — O(n²)
python
def two_sum_brute(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]
Quadratic time; works but slow for len(nums) > 10_000.
Optimal — O(n) with a hash map
python
def two_sum(nums, target):
seen = {} # value -> index
for i, n in enumerate(nums):
if (need := target - n) in seen:
return [seen[need], i]
seen[n] = i
Walk-through for nums = [2, 7, 11, 15], target = 9:
| i | n | need | seen before? | action |
|---|---|---|---|---|
| 0 | 2 | 7 | no | store 2 → 0 |
| 1 | 7 | 2 | yes (index 0) | return [0, 1] |
Tests
python
assert two_sum([2,7,11,15], 9) == [0, 1]
assert two_sum([3,2,4], 6) == [1, 2]
assert two_sum([3,3], 6) == [0, 1]
What interviewers look for
- Can you reach O(n) from O(n²) by trading space for time?
- Walrus operator
:=for "compute once, test, reuse" (Python 3.8+). - Edge cases — negative numbers, duplicates, the same index twice (not allowed).
