Gift Card Waterfall, ZIP Surcharges and Refund Credits
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Simulate a stream of purchase and refund events that drain gift cards by expiry priority, surcharge the card remainder by ZIP range, and turn excess refunds into store credit.
A shop lets customers pay for one purchase with several instruments: any gift cards they hold, and a credit card for whatever is left. You are to build the settlement logic for this. You receive a time-ordered log of events and must report the outcome of each one.
Four sets of rules apply together: spending gift cards before the credit card, expiry and priority among gift cards, ZIP-based surcharges, and refunds.
Function
def settle_payment_events(events: List[str], surcharge_table: List[str]) -> List[str]:
Each element of events is a comma-separated line in one of these formats:
timestamp,ADD_GIFTCARD,customer_id,card_id,amount,valid_before
timestamp,CHARGE,charge_id,customer_id,amount,zip_code
timestamp,REFUND,charge_id,refund_amount
Each element of surcharge_table looks like start_zip-end_zip:rate. For instance 90000-99999:0.05 means any charge whose ZIP code lies in that range (both ends included) pays a 5% surcharge on the part billed to the credit card.
Return a list with exactly one string per event, in the same order as events.
Rules
All money values, in input and output, are non-negative integers in cents (4000 is 40.00 dollars). Print them as plain base-10 integers.
Gift cards and split payment
-
Every customer starts with no cards.
ADD_GIFTCARDgives customercustomer_ida new cardcard_idwith starting balanceamount. Cards have independent balances, one customer may hold many, and a card is only ever spent on its owner's charges. -
The output for
ADD_GIFTCARDis the empty string"". -
A
CHARGEofamountis paid first from the owner's usable cards (defined below), taken in priority order. From each card in turn, take the smaller of the card's balance and the amount still unpaid, and deduct it from the card. A card is fully drained before the next one is touched. Whatever remains unpaid after all usable cards have been consulted is the credit card portion (0 if the cards covered everything). -
The output for a
CHARGEis the final credit card amount followed by one,card_id:amount_useditem for each card that contributed a positive amount:CC_CHARGE,GIFT_CARD_ID_1:AMOUNT_USED,GIFT_CARD_ID_2:AMOUNT_USEDItems appear in ascending
card_idorder, not in the order the cards were drained. If no card was used, the output is just the credit card amount, e.g."1000".CC_CHARGEincludes the surcharge described below.
Expiry and priority
- A card made by
ADD_GIFTCARDis valid at timeTonly whenT < valid_before. WhenT >= valid_beforeit is expired and its leftover balance is gone permanently. - Cards created by refunds (see below) never expire. Since every
ADD_GIFTCARDline has avalid_before, refund-created cards are the only non-expiring ones. - For a charge at time
T, the usable cards are the owner's cards that are valid atTand have a positive balance. They are consumed in this order:- cards with an expiry, earliest
valid_beforefirst; - then cards without an expiry;
- cards sharing the same expiry (including any two non-expiring cards) are ordered by ascending
card_id.
- cards with an expiry, earliest
ZIP surcharges
- Find the range in
surcharge_tablecontaining the charge'szip_code, comparing ZIP codes as integers. If none contains it, the rate is 0. - Only the credit card portion is surcharged; money from gift cards never is.
CC_CHARGE = credit_card_portion + credit_card_portion * rate. For example, a portion of10000at rate0.05yieldsCC_CHARGE = 10500. - The exact value of
credit_card_portion * rateis guaranteed to be a whole number of cents in every input. Output that exact value, with no rounding.
Refunds
For a REFUND of refund_amount against an earlier charge_id:
CC_REFUNDis the smaller ofrefund_amountand theCC_CHARGEthat charge actually billed to the credit card (surcharge included).GC_REFUND = refund_amount - CC_REFUND. If it is positive, create a new card for the customer who made the original charge, withcard_idequal toREFUND_plus the charge id (forchg_1,REFUND_chg_1), balanceGC_REFUND, and no expiry. It then behaves like any other card in later charges. IfGC_REFUNDis 0, no card is created.- A refund never restores balance to the gift cards used by the original charge.
- The output for a
REFUNDisCC_REFUND,GC_REFUND, e.g."10500,1500"or"3000,0".
Ordering of card ids
Whenever card ids are compared, compare them as strings by character code (Python's default string ordering). Uppercase letters come before lowercase ones, so REFUND_chg_1 sorts before gc_2.
Constraints
1 <= len(events) <= 10^4and0 <= len(surcharge_table) <= 1000.- All lines are well formed. Timestamps are integers in
[0, 10^9]and never decrease alongevents; events with equal timestamps take effect in list order. 1 <= valid_before <= 10^9. A card may be added already expired, in which case it is never usable.1 <= amount <= 10^8inADD_GIFTCARDandCHARGElines.customer_id,card_idandcharge_idare 1 to 20 characters of ASCII letters, digits and underscores.card_idvalues inADD_GIFTCARDlines are unique and never begin withREFUND_.charge_idvalues are unique amongCHARGElines.zip_codeis exactly five digits and may have leading zeros. Each range has five-digit bounds withstart_zip <= end_zip, and ranges never overlap.- Each
rateis a decimal with at most 4 digits after the point, in[0, 1]. - Every
REFUNDrefers to aCHARGEappearing earlier, and each charge is refunded at most once.refund_amount >= 1and is at most what was originally paid for that charge (itsamountplus its surcharge). - Every output amount is at most
2 * 10^8. A customer's total balance across cards may exceed2^31 - 1but stays below2^53.
Examples
Example 1
Input: settle_payment_events(['1,ADD_GIFTCARD,cust1,gc1,5000,10', '2,ADD_GIFTCARD,cust1,gc2,4000,5', '3,CHARGE,chg1,cust1,6000,10000', '11,CHARGE,chg2,cust1,1000,10000'], [])
Output: ['', '', '0,gc1:2000,gc2:4000', '1000']
Example 2
Input: settle_payment_events(['1,ADD_GIFTCARD,cust1,gc1,5000,10', '2,CHARGE,chg1,cust1,15000,90210', '3,REFUND,chg1,12000'], ['90000-99999:0.05'])
Output: ['', '10500,gc1:5000', '10500,1500']
Example 3
Input: settle_payment_events(['1,ADD_GIFTCARD,cust_1,gc_1,10000,10', '2,CHARGE,chg_1,cust_1,20000,15000', '3,REFUND,chg_1,21000', '15,CHARGE,chg_2,cust_1,5000,15000', '16,ADD_GIFTCARD,cust_1,gc_2,3000,20', '17,CHARGE,chg_3,cust_1,9000,15000'], ['10000-20000:0.10'])
Output: ['', '11000,gc_1:10000', '11000,10000', '0,REFUND_chg_1:5000', '', '1100,REFUND_chg_1:5000,gc_2:3000']
Hints
Hint 1
For each customer, the usable-card order is a fixed sort key: (valid_before, card_id), with refund-created cards treated as having an infinite valid_before. A min-heap per customer captures this.
Hint 2
Keep balances in a separate dictionary keyed by card_id. The heap only decides order; a partly used card stays at the top. Because timestamps never decrease, an expired or empty card can be popped and discarded permanently.
Hint 3
Do not use floats for the surcharge; use Fraction or integer arithmetic on the rate. Remember each charge as (customer, credit card amount charged) so refunds can split between card money and new store credit. Sort the used-card items by card_id only when formatting the output.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a careful simulation; the main work is choosing data structures so each rule is cheap and exact.
- One min-heap of gift cards per customer. The priority rule is a total order on
(valid_before, card_id). Giving refund-created cardsvalid_before = infinityplaces them after every expiring card, and ties fall back to the card id. Python's tuple and string comparison already gives ASCII ordering. - Balances in a separate dictionary keyed by card id. The heap only decides order, while a partly drained card stays at the top with a smaller balance.
- Lazy deletion. While serving a charge, if the top card is expired (
valid_before <= t) or empty, pop it and continue. Timestamps never decrease, so an expired card stays expired, and an empty card can never be refilled (refunds create new cards instead of topping up old ones). - Exact surcharge. Parse rates as
Fraction, not floats, since10000 * 0.05in floating point can be slightly off. The problem guarantees the product is a whole number of cents, so the exact result converts directly to an integer. - ZIP lookup. Ranges do not overlap, so sort them by start, use
bisect_rightto find the last range starting at or before the ZIP, and check that its end covers the ZIP. - Charge memory. Store
(customer, credit card amount)per charge so a refund knows how much real money can go back and whose store credit to create.
Why it is correct
- Priority: the heap top is the smallest
(valid_before, card_id)among cards not yet discarded. After skipping invalid tops, it is exactly the highest-priority usable card. We takemin(balance, remaining)from it; if it empties it is popped and the next card becomes the top, otherwise the remaining amount is 0 and the loop ends. This matches "drain one card fully before the next". - Discarding is safe: a card popped as expired fails the check at all later times, and an empty card never regains money, so no card that could matter later is lost.
- Output order: the used cards are recorded in drain order and sorted by card id for output. Only positive takes are recorded, so unused cards never appear.
- Surcharge: the rate is applied only to the unpaid remainder, so gift card money is never surcharged.
- Refund:
cc_refund = min(refund, cc_charge)and the rest becomes a new non-expiring cardREFUND_<charge_id>, which is unique because original ids never start withREFUND_and each charge is refunded once.
Complexity
With E events and R surcharge ranges:
- Time:
O(R log R + E log E). Each card is pushed once and popped at most once; each loop iteration within a charge either pops a card or finishes the charge. Sorting used cards is bounded by those pops plus one. ZIP lookup isO(log R). - Space:
O(E + R).
Re-sorting a customer's cards on every charge would be far slower when one customer holds thousands of cards.
Reference solution
import heapq
from bisect import bisect_right
from fractions import Fraction
from typing import List
def settle_payment_events(events: List[str], surcharge_table: List[str]) -> List[str]:
ranges = []
for entry in surcharge_table:
zip_part, rate_text = entry.split(':')
lo, hi = zip_part.split('-')
ranges.append((int(lo), int(hi), Fraction(rate_text)))
ranges.sort()
starts = [r[0] for r in ranges]
INF = float('inf')
heaps = {} # customer -> heap of (valid_before, card_id)
balance = {} # card_id -> remaining balance
charges = {} # charge_id -> (customer, credit card amount)
out = []
for line in events:
parts = line.split(',')
t = int(parts[0])
kind = parts[1]
if kind == 'ADD_GIFTCARD':
cust, card_id, amt, valid_before = parts[2], parts[3], int(parts[4]), int(parts[5])
balance[card_id] = amt
heapq.heappush(heaps.setdefault(cust, []), (valid_before, card_id))
out.append("")
elif kind == 'CHARGE':
charge_id, cust, amt, zip_code = parts[2], parts[3], int(parts[4]), int(parts[5])
heap = heaps.setdefault(cust, [])
remaining = amt
used = []
while remaining > 0 and heap:
valid_before, card_id = heap[0]
if valid_before <= t or balance[card_id] <= 0:
heapq.heappop(heap)
continue
take = min(balance[card_id], remaining)
balance[card_id] -= take
remaining -= take
used.append((card_id, take))
if balance[card_id] == 0:
heapq.heappop(heap)
rate = Fraction(0)
k = bisect_right(starts, zip_code) - 1
if k >= 0 and ranges[k][0] <= zip_code <= ranges[k][1]:
rate = ranges[k][2]
cc = remaining + remaining * rate
cc = int(cc)
charges[charge_id] = (cust, cc)
used.sort()
out.append(','.join([str(cc)] + ['%s:%d' % u for u in used]))
else: # REFUND
charge_id, refund = parts[2], int(parts[3])
cust, cc = charges[charge_id]
cc_refund = min(refund, cc)
gc_refund = refund - cc_refund
if gc_refund > 0:
card_id = 'REFUND_' + charge_id
balance[card_id] = gc_refund
heapq.heappush(heaps.setdefault(cust, []), (INF, card_id))
out.append('%d,%d' % (cc_refund, gc_refund))
return out