← Hash Maps

Drill #26 — Ice cream parlor

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]
O(n) time ยท O(n) space

Related Micro Drills

← Drill #25 Drill #27 →