Finding Pairs with a Map
Given a list of numbers, find two that add up to exactly a target. It's one of the best-known patterns in interview practice and in puzzles, and solving it teaches one big idea: trade memory for time.
The direct way: every pair
for i := 0; i < len(prices); i++ {
for j := i + 1; j < len(prices); j++ {
if prices[i]+prices[j] == budget {
return i, j, true
}
}
}
It's correct, but with n numbers there are about n²/2 pairs. With 100,000 numbers, that's 5 billion checks.
The map way: one pass
When you're at the number p, its partner must be budget - p. So the question isn't "which number fits?" but "has budget - p shown up already?". A map answers that in constant time:
firstAt := make(map[int]int) // price → first index it appeared at
for j, p := range prices {
if i, seen := firstAt[budget-p]; seen {
return i, j, true
}
if _, seen := firstAt[p]; !seen {
firstAt[p] = j
}
}
Two things to watch:
- Check first, store after. If
pis stored before the check, a50with a target of100gets paired with itself. - Store only the first index. When the same price shows up again, don't overwrite it, so the pair you return always uses the earliest index.
Counting every pair
The same pattern can count how many pairs i < j fit. Store how many times each number has appeared so far. When you meet p, every earlier budget - p makes one new pair:
pairs += seen[budget-p]
seen[p]++
Task
You have a gift voucher that must be spent exactly on two different items. The pairForBudget code in the editor already uses the map approach. Read it first, then:
- Complete
countPairs(prices []int, budget int) int: the number of index pairsi < jwithprices[i] + prices[j] == budget, in one pass with a map. A number can appear more than once, and every index pair counts.
The tests check pairForBudget too. Keep its behaviour: the pair whose second item comes earliest, and for that second item, the earliest first item.