Algorithms · Level 1 Hash Maps

Pair Sum with a Hash Map

Find two products that add up exactly to a gift card's value in one pass, with a dict that remembers where each price was seen.

  • dict lookups instead of checking every pair
  • look up the missing amount
  • check before you store

Checking every pair is O(n²). Instead, walk once and keep a dict of what you've seen: for each new price, look up the price that would complete the pair. Trap: check before you store, or one item pairs with itself.

first_seen = {}
for i, order_id in enumerate(order_ids):
    if order_id in first_seen:
        print(order_id, first_seen[order_id])
    first_seen.setdefault(order_id, i)

Write pair_for_budget(prices, budget): the positions (i, j), i < j, of two prices that add up to budget, with the smallest j (then the smallest i), or None. Example: pair_for_budget([20, 50, 30, 70], 100) → (2, 3).

solution.py
Test Suites Pending
Output