Split-Tender Checkout Processor with Expiring Gift Cards
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement process_events(events: list[str], surcharge_rates: list[str]) -> list[str] to simulate a chronological checkout ledger where purchases draw from a customer's gift cards first and bill any remaining balance to their credit card.
Every monetary figure in both the input and output is a non-negative integer count of cents (for instance, 2500 represents $25.00), formatted in base 10 with no decimal points. Return one result string per entry in events, preserving event order.
Event Formats
Each element of events is a comma-delimited string in one of three forms:
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_rates has the form start_zip-end_zip:rate (for example, 75000-79999:0.05), specifying an inclusive numeric ZIP-code interval and its decimal surcharge rate.
Processing Rules
-
Issuing gift cards (
ADD_GIFTCARD):- Customers begin with an empty wallet.
ADD_GIFTCARDgrantscard_idwith starting balanceamountand expiration cutoffvalid_beforeexclusively tocustomer_id(cards never cross customer accounts). - Output
""for everyADD_GIFTCARDevent.
- Customers begin with an empty wallet.
-
Validity & spending priority:
- A card created via
ADD_GIFTCARDis active at event timestampTif and only ifT < valid_beforeand its remaining balance is positive. As soon asT >= valid_before, the card expires and any leftover balance is permanently voided. - Store-credit cards minted during refunds have no expiration cutoff and remain active forever while their balance is positive.
- During a
CHARGEat timestampT, active cards belonging tocustomer_idare spent one by one in this priority order:- Cards with a finite
valid_beforecutoff come ahead of non-expiring refund cards. - Among finite-cutoff cards, smaller
valid_beforevalues come first. - Ties in expiration (including ties among multiple non-expiring refund cards) break by ascending ASCII code-point order of
card_id(so"REFUND_x"precedes"card_1", and"g10"precedes"g9").
- Cards with a finite
- Each card contributes
min(card_balance, unpaid_amount), fully exhausting the current card before moving to the next one.
- A card created via
-
Credit card billing & regional surcharges (
CHARGE):- Whatever portion of
amountremains unpaid after exhausting usable gift cards iscredit_portion(0if gift cards paid the entire purchase). - Match
int(zip_code)against the inclusive intervals insurcharge_rates(int(start_zip) <= int(zip_code) <= int(end_zip)). If no interval matches, userate = 0. - Apply the fee strictly to
credit_portion(gift-card spending is exempt):cc_charge = credit_portion + credit_portion * rate. Inputs guaranteecredit_portion * rateis always an exact integer number of cents. - Format the output string as
cc_chargefollowed by,card_id:cents_usedfor every card that contributed a positive amount, ordered by ascending ASCIIcard_id(not drain order). When no gift card contributed, output onlystr(cc_charge).
- Whatever portion of
-
Refunds (
REFUND):- A
REFUNDofrefund_amountagainst an earliercharge_idreimburses credit-card money before issuing store credit:cc_refund = min(refund_amount, cc_charge), wherecc_chargeis the full credit-card amount billed oncharge_id(including its surcharge).gc_refund = refund_amount - cc_refund.
- Original gift cards spent on
charge_idare never restored. Instead, whenevergc_refund > 0, issue a new non-expiring card to that charge's customer with IDf"REFUND_{charge_id}"and balancegc_refund(create nothing whengc_refund == 0). - Format the output string as
f"{cc_refund},{gc_refund}".
- A
Examples
Example 1
Input:
events = [
"2,ADD_GIFTCARD,u1,card_a,3000,12",
"3,ADD_GIFTCARD,u1,card_b,2500,8",
"5,CHARGE,ord1,u1,4000,30301",
"12,CHARGE,ord2,u1,800,30301",
]
surcharge_rates = []
Output: ["", "", "0,card_a:1500,card_b:2500", "800"]
At T = 5, both cards are active (5 < 8 and 5 < 12). Because card_b expires sooner (8 < 12), it is drained for 2500 first and card_a covers the remaining 1500; the output lists card_a ahead of card_b in ASCII order. By T = 12, card_a has reached its valid_before cutoff (12 >= 12), voiding its remaining 1500 cents so the full 800 goes to the credit card.
Example 2
Input:
events = [
"1,ADD_GIFTCARD,buyer9,promo1,4000,20",
"4,CHARGE,tx1,buyer9,12000,75201",
"6,REFUND,tx1,9500",
]
surcharge_rates = ["75000-79999:0.05"]
Output: ["", "8400,promo1:4000", "8400,1100"]
At T = 4, promo1 pays 4000 of the 12000 purchase, leaving credit_portion = 8000. ZIP 75201 falls inside 75000-79999, adding a 5% fee (400 cents) for cc_charge = 8400. At T = 6, refunding 9500 returns all 8400 to the credit card and mints a non-expiring card REFUND_tx1 holding 1100 cents.
Example 3
Input:
events = [
"1,ADD_GIFTCARD,shopper,v_1,6000,10",
"2,CHARGE,pay_1,shopper,14000,02115",
"5,REFUND,pay_1,13800",
"12,CHARGE,pay_2,shopper,3000,02115",
"14,ADD_GIFTCARD,shopper,v_2,2000,25",
"15,CHARGE,pay_3,shopper,7000,02115",
]
surcharge_rates = ["02000-02999:0.10"]
Output: [
"",
"8800,v_1:6000",
"8800,5000",
"0,REFUND_pay_1:3000",
"",
"3300,REFUND_pay_1:2000,v_2:2000",
]
T = 2:v_1supplies6000;credit_portion = 8000incurs a10%fee at ZIP02115, billing8800.T = 5:8800goes back to the credit card and5000mintsREFUND_pay_1(no expiration).T = 12:REFUND_pay_1covers3000(2000left), socc_charge = 0.T = 15: finite-cutoffv_2(2000, cutoff25) drains ahead of non-expiringREFUND_pay_1(2000), leavingcredit_portion = 3000(cc_charge = 3300). In ASCII order, uppercase'R'precedes lowercase'v', soREFUND_pay_1:2000prints beforev_2:2000.
Constraints
1 <= len(events) <= 10^4and0 <= len(surcharge_rates) <= 1000.0 <= timestamp <= 10^9, non-decreasing acrossevents(equal timestamps execute in list order).1 <= valid_before <= 10^9(a card added withvalid_before <= timestampstarts out already expired).1 <= amount <= 10^8onADD_GIFTCARDandCHARGEevents.customer_id,card_id, andcharge_ideach have length1..20using ASCII letters, digits, and_.ADD_GIFTCARDcard IDs are globally unique and never begin withREFUND_;CHARGEIDs are globally unique.zip_code,start_zip, andend_zipare 5-digit strings (leading zeros permitted) withint(start_zip) <= int(end_zip), and intervals insurcharge_ratesnever overlap.0 <= rate <= 1with at most4digits after the decimal point;credit_portion * rateis guaranteed to be a whole integer.- Every
REFUNDcites a precedingCHARGE, eachcharge_idis refunded at most once, and1 <= refund_amount <= charge_amount + surcharge. - Every individual output integer is
<= 2 * 10^8; one customer's combined card balance can exceed2^31 - 1while remaining< 2^53.
Step-by-step walkthrough
Understand all four rule layers at a glance
We simulate a chronological payment stream and return one output string per event:
ADD_GIFTCARD: addscard_idwithamountcents and cutoffvalid_beforetocustomer_id. Always outputs"".CHARGE: paysamountforcustomer_idusing their active gift cards first, charges the leftovercredit_portionplus any regional ZIP surcharge to their credit card, and outputs"CC_CHARGE,card1:used1,card2:used2,..."(or just"CC_CHARGE"if no gift card was used).REFUND: refundsrefund_amountagainst an earliercharge_id, returning credit-card funds up toCC_CHARGEfirst and turning any remainderGC_REFUNDinto a new non-expiring gift card named"REFUND_" + charge_id. Outputs"CC_REFUND,GC_REFUND".
Four subtle rules decide whether a solution passes every edge case:
- Strict expiry boundary (
<, not<=): A gift card is active at timestampTonly whenT < valid_before. AtT == valid_before, its remaining balance is already permanently void. - Three-level spending priority: Finite-expiry cards come first (earliest
valid_beforefirst); non-expiringREFUND_...cards come after all finite cards; ties break by ascending ASCIIcard_id("REFUND_x" < "card_1","g10" < "g9"). - Drain order vs. output order: You spend cards in priority order, but the
CHARGEoutput string lists used cards sorted in ascending ASCII order ofcard_id. - Exact cents & refund cap: Surcharges apply only to
credit_portionwithout float rounding bugs, andCC_REFUNDis capped at the fullCC_CHARGE(including surcharge), never restoring balance to old drained gift cards.
Why re-sorting cards on every charge is too slow
With up to
10,000events, one customer could receive5,000gift cards of2cents each, followed by5,000charges of1cent each.If every
CHARGEfiltered and sorted all5,000cards from scratch (O(C log C)per charge) and linearly scanned all1,000surcharge ranges (O(R)per charge), we would perform roughly25,000,000card checks plus5,000sorts and5,000,000ZIP comparisons.Notice why that work is wasted: a card's priority never changes after creation, timestamps never move backward, and the ZIP surcharge table never changes. A per-customer min-heap plus binary search on sorted ZIP ranges removes all repeated work.
Key idea: per-customer min-heap with lazy expiry
For each customer, we keep a Python
heapqmin-heap where every card is a 4-element list:Heap entry: [expiry_group, valid_before, card_id, balance] | | | | | | | +-- 4th: mutable cents left (never compared, | | | because every card_id is unique!) | | +------------ 3rd: ASCII tie-breaker ("g10" < "g9") | +------------------------- 2nd: earliest expiration first (0 for NO_EXPIRY) +---------------------------------------- 1st: 0 = HAS_EXPIRY, 1 = NO_EXPIRYWhy can we handle card expiration simply by popping expired cards from the top (
cards[0]) right before spending? Follow two invariants:Min-heap top (`cards[0]`): Case 1: cards[0] has HAS_EXPIRY (0) and valid_before <= now -> Expired! And since timestamps never decrease, it stays expired forever -> pop it! Case 2: Loop stops because cards[0] has NO_EXPIRY (1), OR valid_before > now -> Every other finite card in the heap has valid_before >= cards[0].valid_before > now, and every NO_EXPIRY card never expires. -> Therefore EVERY card currently inside the heap is guaranteed valid at `now`!Because every card is pushed once and popped at most once (either when it expires or when its balance hits
0), all heap work across allEevents totalsO(E log E)!Drain gift cards in priority order
Inside
spend_gift_cards(cards, amount, now):- First, pop expired cards from
cards[0]whilecards[0][0] == HAS_EXPIRY and cards[0][1] <= now. - Next, while
unpaid > 0andcardsis non-empty, peek attop_card = cards[0]and takemin(available_balance, unpaid). - Subtract
takefromtop_card[3]in place. Iftop_card[3]reaches0, pop it immediately so zero-balance cards never linger in the heap; if money remains ontop_card,unpaidis now0andtop_cardstays cleanly at the root for future charges.
from typing import Any, Dict, List, Tuple import heapq HAS_EXPIRY = 0 NO_EXPIRY = 1 def spend_gift_cards( cards: List[List[Any]], amount: int, now: int ) -> Tuple[int, Dict[str, int]]: """Drain usable cards in priority order; return (unpaid_amount, {card_id: amount_used}).""" # Lazy expiry: finite-expiry cards sit ahead of non-expiring cards, earliest valid_before first. # A card is valid only when `now < valid_before`, so `valid_before <= now` means it has expired. while cards and cards[0][0] == HAS_EXPIRY and cards[0][1] <= now: heapq.heappop(cards) used_cards: Dict[str, int] = {} unpaid = amount # Drain the highest-priority valid card at `cards[0]` until `unpaid == 0` or no cards remain. while unpaid > 0 and cards: top_card = cards[0] card_id = top_card[2] available_balance = top_card[3] take = min(available_balance, unpaid) # Mutating balance at index 3 in place preserves heap order because `card_id` (index 2) is unique. top_card[3] -= take unpaid -= take used_cards[card_id] = take if top_card[3] == 0: heapq.heappop(cards) return unpaid, used_cards- First, pop expired cards from
Compute exact ZIP surcharges with binary search and Fractions
Never multiply money by binary
floatrates: in IEEE 754 floating point,10000 * 0.57evaluates to5699.999999999999, soint(10000 * 0.57)silently loses a cent and gives5699! Python'sfractions.Fraction("0.57")stores the exact rational number57 / 100, makingint(credit_portion * rate)100% exact.Because surcharge ZIP ranges never overlap, sorting them once by
start_zipletsbisect_rightfind the only possible matching interval inO(log R)steps:Sorted non-overlapping ranges: [02000..02999] [30000..39999] [75000..79999] starts: 2000 30000 75000 ends: 2999 39999 79999 Query zip_code = 2115 ("02115"): bisect_right(starts, 2115) - 1 -> idx = 0 (start 2000 <= 2115) check 2115 <= ends[0] (2999) -> True! Return rates[0]. Query zip_code = 50000 (in a gap): bisect_right(starts, 50000) - 1 -> idx = 1 (start 30000 <= 50000) check 50000 <= ends[1] (39999) -> False! Return Fraction(0).from fractions import Fraction from typing import List, Tuple import bisect def parse_surcharge_ranges( surcharge_rates: List[str], ) -> Tuple[List[int], List[int], List[Fraction]]: """Parse 'start-end:rate' strings into three parallel lists sorted by start ZIP.""" # ranges: list of (start_zip, end_zip, exact_fraction_rate) tuples ranges: List[Tuple[int, int, Fraction]] = [] for entry in surcharge_rates: zip_part, rate_text = entry.split(":") start_text, end_text = zip_part.split("-") # Use Fraction(rate_text) instead of float so e.g. 10000 * Fraction("0.57") == 5700, not 5699. ranges.append((int(start_text), int(end_text), Fraction(rate_text))) ranges.sort() starts: List[int] = [] ends: List[int] = [] rates: List[Fraction] = [] for start_zip, end_zip, rate in ranges: starts.append(start_zip) ends.append(end_zip) rates.append(rate) return starts, ends, rates def find_rate( zip_code: int, starts: List[int], ends: List[int], rates: List[Fraction] ) -> Fraction: """Return the exact surcharge Fraction covering `zip_code`, or Fraction(0) if none matches.""" # Since ranges never overlap, only the last range with start_zip <= zip_code can cover `zip_code`. idx = bisect.bisect_right(starts, zip_code) - 1 if idx >= 0 and zip_code <= ends[idx]: return rates[idx] return Fraction(0)Process charges, refunds, and trace Example 3
Each
CHARGEsavescharges[charge_id] = (customer_id, cc_charge)so a laterREFUNDknows both who owns the charge and the maximum credit-card refundcc_charge. Whengc_refund = refund_amount - cc_refundis positive, we push[NO_EXPIRY, 0, f"REFUND_{charge_id}", gc_refund]onto that customer's heap.Let's trace Example 3 (
surcharge_rates = ["02000-02999:0.10"]) to watch finite cards and refund cards interact insideshopper's heap:t=1 ADD_GIFTCARD v_1, amount=6000, valid_before=10 heap: [[0, 10, "v_1", 6000]] -> "" t=2 CHARGE pay_1, amount=14000, zip=02115 (10% surcharge) drains v_1 for 6000 (popped); credit_portion=8000 -> +800=8800 charges["pay_1"] = ("shopper", 8800), heap: [] -> "8800,v_1:6000" t=5 REFUND pay_1, refund_amount=13800 cc_refund = min(13800, 8800) = 8800; gc_refund = 5000 heap: [[1, 0, "REFUND_pay_1", 5000]] -> "8800,5000" t=12 CHARGE pay_2, amount=3000, zip=02115 top is NO_EXPIRY; takes 3000 from REFUND_pay_1 (2000 left) credit_portion=0 -> cc_charge=0 -> "0,REFUND_pay_1:3000" t=14 ADD_GIFTCARD v_2, amount=2000, valid_before=25 heap: [[0, 25, "v_2", 2000], [1, 0, "REFUND_pay_1", 2000]] -> "" t=15 CHARGE pay_3, amount=7000, zip=02115 1st drains finite v_2 (2000, popped), 2nd drains REFUND_pay_1 (2000, popped) credit_portion=3000 -> +300=3300 output sorts card IDs in ASCII ('R' < 'v'): -> "3300,REFUND_pay_1:2000,v_2:2000"Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import bisect import heapq from fractions import Fraction # Heap priority group constants: finite-expiry cards (0) always sort before non-expiring refund cards (1). HAS_EXPIRY = 0 NO_EXPIRY = 1 def parse_surcharge_ranges( surcharge_rates: List[str], ) -> Tuple[List[int], List[int], List[Fraction]]: """Parse 'start-end:rate' strings into three parallel lists sorted by start ZIP.""" # ranges: list of (start_zip, end_zip, exact_fraction_rate) tuples ranges: List[Tuple[int, int, Fraction]] = [] for entry in surcharge_rates: zip_part, rate_text = entry.split(":") start_text, end_text = zip_part.split("-") # Use Fraction(rate_text) instead of float so e.g. 10000 * Fraction("0.57") == 5700, not 5699. ranges.append((int(start_text), int(end_text), Fraction(rate_text))) ranges.sort() starts: List[int] = [] ends: List[int] = [] rates: List[Fraction] = [] for start_zip, end_zip, rate in ranges: starts.append(start_zip) ends.append(end_zip) rates.append(rate) return starts, ends, rates def find_rate( zip_code: int, starts: List[int], ends: List[int], rates: List[Fraction] ) -> Fraction: """Return the exact surcharge Fraction covering `zip_code`, or Fraction(0) if none matches.""" # Since ranges never overlap, only the last range with start_zip <= zip_code can cover `zip_code`. idx = bisect.bisect_right(starts, zip_code) - 1 if idx >= 0 and zip_code <= ends[idx]: return rates[idx] return Fraction(0) def spend_gift_cards( cards: List[List[Any]], amount: int, now: int ) -> Tuple[int, Dict[str, int]]: """Drain usable cards in priority order; return (unpaid_amount, {card_id: amount_used}).""" # Lazy expiry: finite-expiry cards sit ahead of non-expiring cards, earliest valid_before first. # A card is valid only when `now < valid_before`, so `valid_before <= now` means it has expired. while cards and cards[0][0] == HAS_EXPIRY and cards[0][1] <= now: heapq.heappop(cards) used_cards: Dict[str, int] = {} unpaid = amount # Drain the highest-priority valid card at `cards[0]` until `unpaid == 0` or no cards remain. while unpaid > 0 and cards: top_card = cards[0] card_id = top_card[2] available_balance = top_card[3] take = min(available_balance, unpaid) # Mutating balance at index 3 in place preserves heap order because `card_id` (index 2) is unique. top_card[3] -= take unpaid -= take used_cards[card_id] = take if top_card[3] == 0: heapq.heappop(cards) return unpaid, used_cards def process_events(events: list[str], surcharge_rates: list[str]) -> list[str]: starts, ends, rates = parse_surcharge_ranges(surcharge_rates) # cards_by_customer: customer_id -> min-heap of [expiry_group, valid_before, card_id, balance] cards_by_customer: Dict[str, List[List[Any]]] = {} # charges: charge_id -> (customer_id, cc_charge_including_surcharge) charges: Dict[str, Tuple[str, int]] = {} output: List[str] = [] for line in events: parts = line.split(",") now = int(parts[0]) kind = parts[1] if kind == "ADD_GIFTCARD": customer_id, card_id = parts[2], parts[3] amount, valid_before = int(parts[4]), int(parts[5]) cards = cards_by_customer.setdefault(customer_id, []) heapq.heappush(cards, [HAS_EXPIRY, valid_before, card_id, amount]) output.append("") elif kind == "CHARGE": charge_id, customer_id = parts[2], parts[3] amount, zip_code = int(parts[4]), int(parts[5]) cards = cards_by_customer.setdefault(customer_id, []) credit_portion, used_cards = spend_gift_cards(cards, amount, now) rate = find_rate(zip_code, starts, ends, rates) # Surcharge applies ONLY to `credit_portion`, and the input guarantees exact whole cents. surcharge = int(credit_portion * rate) cc_charge = credit_portion + surcharge charges[charge_id] = (customer_id, cc_charge) # Output lists used cards in ascending ASCII `card_id` order, NOT drain order. pieces = [str(cc_charge)] for card_id in sorted(used_cards): pieces.append(f"{card_id}:{used_cards[card_id]}") output.append(",".join(pieces)) else: # REFUND charge_id, refund_amount = parts[2], int(parts[3]) customer_id, cc_charge = charges[charge_id] # Refund real money up to `cc_charge` (surcharge included) first; excess becomes store credit. cc_refund = min(refund_amount, cc_charge) gc_refund = refund_amount - cc_refund if gc_refund > 0: cards = cards_by_customer.setdefault(customer_id, []) heapq.heappush(cards, [NO_EXPIRY, 0, f"REFUND_{charge_id}", gc_refund]) output.append(f"{cc_refund},{gc_refund}") return output✅ Submit now — all tests should pass.
Intuition & how it works
In a split-tender transaction (a single purchase paid across multiple payment methods), think of each customer as carrying a smart coupon wallet that automatically keeps the coupon expiring soonest right at the front, followed by never-expiring store-credit coupons at the very back. We give each customer a min-heap (a binary tree stored in a list whose highest-priority item sits at index 0 and updates in O(log N) time) storing [expiry_group, valid_before, card_id, balance] and use lazy expiry (ignoring expired cards until a customer actually makes a purchase, then popping expired cards from index 0 until the front card is active). Any leftover balance goes to the credit card with a regional fee found via binary search (repeatedly halving a sorted list of non-overlapping ZIP intervals) and computed with exact rational arithmetic (fractions.Fraction, which stores "0.05" as exact 1 / 20 rather than an approximate binary float).
Why do naive implementations fail or time out? First, re-filtering and re-sorting all of a customer's gift cards on every purchase degrades to O(E^2 log E) when one customer holds 5,000 small cards across 5,000 tiny purchases, whereas a min-heap pushes and pops each card at most once across the entire run. Second, multiplying cents by a Python float introduces binary rounding drift: 10000 * 0.57 evaluates to 5699.999999999999, so int(...) truncates it to 5699 instead of 5700!
Let's walk through a 4-event trace with surcharge_rates = ["75000-79999:0.05"]:
1. t=1 ADD_GIFTCARD u1, card_a=3000 (exp 12) -> heap: [[0, 12, "card_a", 3000]] -> ""
2. t=2 ADD_GIFTCARD u1, card_b=2500 (exp 8) -> heap: [[0, 8, "card_b", 2500], [0, 12, "card_a", 3000]] -> ""
3. t=4 CHARGE tx1, u1, 13500, zip=75201:
- drains card_b (2500, popped), then card_a (3000, popped); credit_portion = 8000
- ZIP 75201 matches 0.05 -> surcharge = 400 -> cc_charge = 8400
- output sorts used IDs in ASCII ("card_a" before "card_b") -> "8400,card_a:3000,card_b:2500"
4. t=6 REFUND tx1, 9500:
- cc_refund = min(9500, 8400) = 8400; gc_refund = 1100
- pushes non-expiring [1, 0, "REFUND_tx1", 1100] onto u1's heap -> "8400,1100"
Complexity
Let E be the number of events (E <= 10^4) and R be the number of surcharge ranges (R <= 1,000).
- Time:
O(R log R + E log E + E log R). Parsing and sorting theRsurcharge ranges once at startup takesO(R log R)time, and eachCHARGEfinds its surcharge rate with oneO(log R)binary search. Across the entire stream ofEevents, at mostEgift/refund cards are ever created; each card is pushed onto a heap once (O(log E)) and popped at most once when it expires or reaches zero balance (O(log E)), plus at most one partially drained card perCHARGEis updated inO(1)time without popping. Thus the amortized time (average cost per event spread across the entire sequence) for heap updates and sorting used card IDs (sum(k log k) <= E log E) isO(log E)per event. - Space:
O(E + R). The sorted surcharge arrays storeRentries, whilecards_by_customer,charges, andoutputstore at most one entry per event (O(E)).
Edge cases
- Exact expiration boundary (
T == valid_before): Because validity requiresT < valid_before, a card withvalid_before = 12is active atT = 11and popped as expired atT = 12(valid_before <= now). - Card added already expired (
valid_before <= add_time): Safely pushed onADD_GIFTCARDand immediately discarded by lazy expiry before the customer's next charge. - Drain order differs from output order: In Example 1,
card_bexpires earlier (8 < 12) so it is drained first, yet"card_a"comes before"card_b"in lexicographical (ASCII) order (character-by-character code-point comparison), so the output prints"0,card_a:1500,card_b:2500". Similarly, uppercase'R'precedes lowercase'v', so"REFUND_pay_1"prints before"v_2". - Zero credit-card portion or zero gift-card usage: When gift cards cover the entire charge,
credit_portion = 0andcc_charge = 0(surcharge on0is0). When no gift cards are used, the output has no trailing comma (just"800"). - Refund exactly equal to
CC_CHARGE:gc_refund == 0, so noREFUND_<charge_id>card is pushed onto the heap, and the output ends with,0. - Leading-zero ZIP codes (
"02115"): Converted withint(...)to2115and matched inclusively (start_zip <= zip_code <= end_zip); ZIPs falling in gaps between ranges default toFraction(0).
Common mistakes
- Using
floatfor surcharge rates: Expressions likeint(100 * 0.29)(28) orint(10000 * 0.57)(5699) lose 1 cent due to binary floating-point representation; always useFraction(or integer basis pointsrate_ten_thousandths // 10000). - Applying the surcharge to the total purchase
amount: Onlycredit_portion(after subtracting gift cards) incurs the regional surcharge. - Capping
CC_REFUNDat the pre-surchargecredit_portion: Credit-card refunds are capped atCC_CHARGEincluding the surcharge (e.g.,8400in Example 2, not8000). - Restoring refund cents onto the original gift cards: Refunds never replenish spent gift cards (which might already have expired); excess refund always creates a brand-new non-expiring
REFUND_<charge_id>card. - Using
<instead of<=in lazy expiry (cards[0][1] < now): Allows a card to be spent on the exact timestampnow == valid_beforewhen it is already void. - Printing used cards in drain order: Forgetting
sorted(used_cards)fails whenever an earlier-expiring card has a lexicographically larger ID.
Alternative approaches
- Scaled integer ten-thousandths instead of
Fraction: Since every rate has at most 4 decimal places, you can parse"0.0125"into the integer125(zero-padding to 4 decimal places) and compute(credit_portion * rate_bps) // 10000with pure integer math.Fraction(rate_text)achieves the same exactness in one standard-library call with zero custom string padding.
Follow-up questions
- How would you support multiple partial refunds against the same charge instead of at most one refund? Store
remaining_cc_refundable(initialized tocc_charge) andremaining_total_refundable(initialized toamount + surcharge) percharge_id. On each partial refund, returncc_refund = min(refund_amount, remaining_cc_refundable)to the credit card, decrementremaining_cc_refundablebycc_refund, and issue the remaindergc_refundeither onto a numbered card likeREFUND_<charge_id>_<seq>or by adding balance to an existingREFUND_<charge_id>card (re-pushing it if it had previously been drained to zero). - What changes if surcharge percentages can produce fractional cents rather than exact integer amounts? Agree on an explicit rounding policy — such as half-up (
0.5 cents -> 1 cent) or banker's rounding (rounding exact.5ties to the nearest even cent so upward and downward rounding cancel out over millions of transactions). Compute the exact rational value withFractionordecimal.Decimal, apply the chosen rounding rule once to computesurcharge, and store that exact integercc_chargeso refunds never recompute or re-round fees. - Why does lazy heap eviction fail when payment events arrive out of chronological order, and how would you handle late events? Lazy heap deletion breaks when timestamps jump backward, because a card popped at
t = 12might still have been valid for a late-arriving charge att = 5, and spending att = 5changes what remains att = 12! If late events must take effect retroactively at their event timestamp, append raw events to a log and either buffer within a bounded watermark window before running our heap processor in timestamp order, or replay affected customer histories from periodic state snapshots.
Follow-up questions
- How would you support multiple partial refunds against the same charge instead of at most one refund?
- What changes if surcharge percentages can produce fractional cents rather than exact integer amounts?
- Why does lazy heap eviction fail when payment events arrive out of chronological order, and how would you handle late events?
Similar questions
- Pull Request Reviewer Selection via File Ownership
- Task Scheduling with Worker Account Affinity
- Credit-Backed Account Transfer Ledger
- Monthly Invoice Calculator with Tiered Usage
- Merchant Payment Fee Engine for CSV Logs
- Multi-Currency Ledger with Overdraft Coverage
More Stripe interview questions
- Schedule Weekly Release Slots Around Freeze Windows Medium
- Event-Driven Subscription Notification Scheduler Medium
- Rewinding Stream Request Bodies Across HTTP 307/308 Redirects Medium Pro
- Connected User Profiles via Weighted Similarity Medium Pro
- Three-Tier Payment-to-Invoice Reconciliation Medium Pro
- Reconcile Payments Against Invoices Easy Pro
- Post Moderation Policy Engine With Chained Boolean Rules Hard Pro
- Left-to-Right Payment Rule Evaluator with Grouped Conditions Hard Pro
- Spherical Distance and Healthy Region Routing Medium Pro
- Priority-Based Invoice Payment Reconciliation Medium Pro