1Question
You are given an array of numbers nums and a number target. Find two different positions whose numbers add up to target, and return their indices.
There is exactly one answer. You can not use the same position twice, but two positions can hold the same value (like [3, 3]). You may return the indices in any order.
nums[0] + nums[1] = 2 + 7 = 9.
2 + 4 = 6. Using 3 twice is not allowed, because it is one position.
Two different positions with the same value are fine.
Constraints
Up to 10,000 numbers. Checking every pair is about 50 million checks: it passes, but we can do it in O(n).
Values can be negative and very large, so we use a hash map, not an array of counts.
Can you find an algorithm faster than O(n²)? Yes: one pass with a hash map.
2Hints
Open one hint at a time. Try to think before you open the next one.
3Pattern
Hash Map Complement
Remember what you passed so that you can find a partner in O(1).
For a pair problem, fixing one number tells you exactly what the other one must be. A hash map stores value → index, so we can jump straight to the partner:
Every number is looked up once and saved once. The second loop of the brute force disappears.
How to spot this pattern
- You need two items that combine to a goal (sum, difference, product).
- Given one item, the other one is fully decided.
- You must return positions, so sorting would lose them.
- You are allowed O(n) extra memory.
4Explanation
The big idea: Walk through the array once with a map called seen (value → index). At each number:
Work out need = target − num. If need is in the map, return [seen[need], i].
Not found? Save seen[num] = i so a later number can pair with this one.
Why does one pass work? The answer pair has a first and a second position. When we reach the second one, the first is already in the map, so the lookup finds it.
Why check before saving? With [3, 3] and target 6, the first 3 looks for 3 and must not find itself. Saving after the lookup makes sure of that.
5Brute Force
Try every pair of positions.
Idea
A pair is two positions i and j with i before j. So we:
- Pick every first position
i. - Try every later position
j. - If
nums[i] + nums[j] == target, return[i, j].
def two_sum_brute(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n): # j starts after i, so no position is used twice
if nums[i] + nums[j] == target:
return [i, j]
return []
print(two_sum_brute([2, 7, 11, 15], 9)) # [0, 1]6Optimal Solution
One pass with a hash map of value → index.
def two_sum(nums, target):
seen = {} # value -> index
for i, num in enumerate(nums):
need = target - num # the partner we are looking for
if need in seen: # O(1) lookup
return [seen[need], i]
seen[num] = i # save AFTER the check
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]7Time and Space Complexity
Let n be the number of items in the array.
Brute force
Optimal (hash map)
How big is the difference?
Approximate number of steps:
| n | Brute force (n²/2) | Hash map (n) |
|---|---|---|
| 10 | 45 | 10 |
| 1,000 | 499,500 | 1,000 |
| 10,000 | about 50 million | 10,000 |
For the biggest input in this problem, the hash map does around 5,000 times less work.