Easy Complement Map Hash Maps
In plain English: Given ice cream prices and a budget, find two flavors that cost exactly the budget.
Same as two-sum: for each price, check if budget minus price has already been seen.
Prompt
Given prices and a budget, find two items that sum to exactly the budget.
Try to write it from scratch before scrolling down.
Solution
def ice_cream(prices, money):
seen = {}
for i, p in enumerate(prices):
complement = money - p
if complement in seen:
return [seen[complement] + 1, i + 1] # 1-indexed
seen[p] = i
return []
# Test: ice_cream([1,4,5,3,2], 4) == [1, 4]