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:
- By method:
"CREDIT", then"CARD", then"PAYPAL", then other methods alphabetically. - Within a method, larger
timestampfirst; ties by smallerpayment_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.