progress

~/problems / Greedy

Splitting a refund across payments

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Airbnb

A guest paid for a trip in several pieces, some already partly refunded. Support wants to give back amount more cents. Decide how much goes back to each payment.

def allocate_refund(
    payments: list[tuple[str, str, int, int]],
    past_refunds: list[tuple[str, str, int]],
    amount: int,
) -> list[tuple[str, int]]
  • payments[i] = (payment_id, method, timestamp, paid), unique ids, paid > 0.
  • past_refunds[j] = (refund_id, payment_id, refunded). Refunds for unknown payment ids are ignored.

A payment's balance is paid minus its past refunds, never below 0. Fill the refund greedily in this order:

  1. By method: "CREDIT", then "CARD", then "PAYPAL", then other methods alphabetically.
  2. Within a method, larger timestamp first; ties by smaller payment_id.

Each payment takes min(balance, what is left). Return (payment_id, cents) pairs in allocation order, skipping zeros. If the total balance is below amount, or amount == 0, return [].

payments = [
    ("p1", "CARD",   100, 5000),
    ("p2", "CREDIT", 50,  1000),
    ("p3", "CARD",   200, 3000),
    ("p4", "GIFT",   300, 2000),
]
past = [("r1", "p3", 2500), ("r2", "p2", 400)]
allocate_refund(payments, past, 4000)
# balances: p1 5000, p2 600, p3 500, p4 2000
# -> [("p2", 600), ("p3", 500), ("p1", 2900)]
allocate_refund(payments, past, 9000)   # [] : only 8100 is refundable

⭐ Bonus: a speed test with 100,000 payments and 100,000 refunds earns a star if you total the refunds per payment first instead of scanning them all for every payment.

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc