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

  1. Issuing gift cards (ADD_GIFTCARD):

    • Customers begin with an empty wallet. ADD_GIFTCARD grants card_id with starting balance amount and expiration cutoff valid_before exclusively to customer_id (cards never cross customer accounts).
    • Output "" for every ADD_GIFTCARD event.
  2. Validity & spending priority:

    • A card created via ADD_GIFTCARD is active at event timestamp T if and only if T < valid_before and its remaining balance is positive. As soon as T >= 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 CHARGE at timestamp T, active cards belonging to customer_id are spent one by one in this priority order:
      1. Cards with a finite valid_before cutoff come ahead of non-expiring refund cards.
      2. Among finite-cutoff cards, smaller valid_before values come first.
      3. 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").
    • Each card contributes min(card_balance, unpaid_amount), fully exhausting the current card before moving to the next one.
  3. Credit card billing & regional surcharges (CHARGE):

    • Whatever portion of amount remains unpaid after exhausting usable gift cards is credit_portion (0 if gift cards paid the entire purchase).
    • Match int(zip_code) against the inclusive intervals in surcharge_rates (int(start_zip) <= int(zip_code) <= int(end_zip)). If no interval matches, use rate = 0.
    • Apply the fee strictly to credit_portion (gift-card spending is exempt): cc_charge = credit_portion + credit_portion * rate. Inputs guarantee credit_portion * rate is always an exact integer number of cents.
    • Format the output string as cc_charge followed by ,card_id:cents_used for every card that contributed a positive amount, ordered by ascending ASCII card_id (not drain order). When no gift card contributed, output only str(cc_charge).
  4. Refunds (REFUND):

    • A REFUND of refund_amount against an earlier charge_id reimburses credit-card money before issuing store credit:
      • cc_refund = min(refund_amount, cc_charge), where cc_charge is the full credit-card amount billed on charge_id (including its surcharge).
      • gc_refund = refund_amount - cc_refund.
    • Original gift cards spent on charge_id are never restored. Instead, whenever gc_refund > 0, issue a new non-expiring card to that charge's customer with ID f"REFUND_{charge_id}" and balance gc_refund (create nothing when gc_refund == 0).
    • Format the output string as f"{cc_refund},{gc_refund}".

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_1 supplies 6000; credit_portion = 8000 incurs a 10% fee at ZIP 02115, billing 8800.
  • T = 5: 8800 goes back to the credit card and 5000 mints REFUND_pay_1 (no expiration).
  • T = 12: REFUND_pay_1 covers 3000 (2000 left), so cc_charge = 0.
  • T = 15: finite-cutoff v_2 (2000, cutoff 25) drains ahead of non-expiring REFUND_pay_1 (2000), leaving credit_portion = 3000 (cc_charge = 3300). In ASCII order, uppercase 'R' precedes lowercase 'v', so REFUND_pay_1:2000 prints before v_2:2000.

Constraints

  • 1 <= len(events) <= 10^4 and 0 <= len(surcharge_rates) <= 1000.
  • 0 <= timestamp <= 10^9, non-decreasing across events (equal timestamps execute in list order).
  • 1 <= valid_before <= 10^9 (a card added with valid_before <= timestamp starts out already expired).
  • 1 <= amount <= 10^8 on ADD_GIFTCARD and CHARGE events.
  • customer_id, card_id, and charge_id each have length 1..20 using ASCII letters, digits, and _. ADD_GIFTCARD card IDs are globally unique and never begin with REFUND_; CHARGE IDs are globally unique.
  • zip_code, start_zip, and end_zip are 5-digit strings (leading zeros permitted) with int(start_zip) <= int(end_zip), and intervals in surcharge_rates never overlap.
  • 0 <= rate <= 1 with at most 4 digits after the decimal point; credit_portion * rate is guaranteed to be a whole integer.
  • Every REFUND cites a preceding CHARGE, each charge_id is refunded at most once, and 1 <= refund_amount <= charge_amount + surcharge.
  • Every individual output integer is <= 2 * 10^8; one customer's combined card balance can exceed 2^31 - 1 while remaining < 2^53.

Step-by-step walkthrough

  1. Understand all four rule layers at a glance

    We simulate a chronological payment stream and return one output string per event:

    • ADD_GIFTCARD: adds card_id with amount cents and cutoff valid_before to customer_id. Always outputs "".
    • CHARGE: pays amount for customer_id using their active gift cards first, charges the leftover credit_portion plus 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: refunds refund_amount against an earlier charge_id, returning credit-card funds up to CC_CHARGE first and turning any remainder GC_REFUND into 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:

    1. Strict expiry boundary (<, not <=): A gift card is active at timestamp T only when T < valid_before. At T == valid_before, its remaining balance is already permanently void.
    2. Three-level spending priority: Finite-expiry cards come first (earliest valid_before first); non-expiring REFUND_... cards come after all finite cards; ties break by ascending ASCII card_id ("REFUND_x" < "card_1", "g10" < "g9").
    3. Drain order vs. output order: You spend cards in priority order, but the CHARGE output string lists used cards sorted in ascending ASCII order of card_id.
    4. Exact cents & refund cap: Surcharges apply only to credit_portion without float rounding bugs, and CC_REFUND is capped at the full CC_CHARGE (including surcharge), never restoring balance to old drained gift cards.
  2. Why re-sorting cards on every charge is too slow

    With up to 10,000 events, one customer could receive 5,000 gift cards of 2 cents each, followed by 5,000 charges of 1 cent each.

    If every CHARGE filtered and sorted all 5,000 cards from scratch (O(C log C) per charge) and linearly scanned all 1,000 surcharge ranges (O(R) per charge), we would perform roughly 25,000,000 card checks plus 5,000 sorts and 5,000,000 ZIP 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.

  3. Key idea: per-customer min-heap with lazy expiry

    For each customer, we keep a Python heapq min-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_EXPIRY
    

    Why 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 all E events totals O(E log E)!

  4. Drain gift cards in priority order

    Inside spend_gift_cards(cards, amount, now):

    1. First, pop expired cards from cards[0] while cards[0][0] == HAS_EXPIRY and cards[0][1] <= now.
    2. Next, while unpaid > 0 and cards is non-empty, peek at top_card = cards[0] and take min(available_balance, unpaid).
    3. Subtract take from top_card[3] in place. If top_card[3] reaches 0, pop it immediately so zero-balance cards never linger in the heap; if money remains on top_card, unpaid is now 0 and top_card stays 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
    
  5. Compute exact ZIP surcharges with binary search and Fractions

    Never multiply money by binary float rates: in IEEE 754 floating point, 10000 * 0.57 evaluates to 5699.999999999999, so int(10000 * 0.57) silently loses a cent and gives 5699! Python's fractions.Fraction("0.57") stores the exact rational number 57 / 100, making int(credit_portion * rate) 100% exact.

    Because surcharge ZIP ranges never overlap, sorting them once by start_zip lets bisect_right find the only possible matching interval in O(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)
    
  6. Process charges, refunds, and trace Example 3

    Each CHARGE saves charges[charge_id] = (customer_id, cc_charge) so a later REFUND knows both who owns the charge and the maximum credit-card refund cc_charge. When gc_refund = refund_amount - cc_refund is 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 inside shopper'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"
    
  7. 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 the R surcharge ranges once at startup takes O(R log R) time, and each CHARGE finds its surcharge rate with one O(log R) binary search. Across the entire stream of E events, at most E gift/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 per CHARGE is updated in O(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) is O(log E) per event.
  • Space: O(E + R). The sorted surcharge arrays store R entries, while cards_by_customer, charges, and output store at most one entry per event (O(E)).

Edge cases

  • Exact expiration boundary (T == valid_before): Because validity requires T < valid_before, a card with valid_before = 12 is active at T = 11 and popped as expired at T = 12 (valid_before <= now).
  • Card added already expired (valid_before <= add_time): Safely pushed on ADD_GIFTCARD and immediately discarded by lazy expiry before the customer's next charge.
  • Drain order differs from output order: In Example 1, card_b expires 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 = 0 and cc_charge = 0 (surcharge on 0 is 0). When no gift cards are used, the output has no trailing comma (just "800").
  • Refund exactly equal to CC_CHARGE: gc_refund == 0, so no REFUND_<charge_id> card is pushed onto the heap, and the output ends with ,0.
  • Leading-zero ZIP codes ("02115"): Converted with int(...) to 2115 and matched inclusively (start_zip <= zip_code <= end_zip); ZIPs falling in gaps between ranges default to Fraction(0).

Common mistakes

  • Using float for surcharge rates: Expressions like int(100 * 0.29) (28) or int(10000 * 0.57) (5699) lose 1 cent due to binary floating-point representation; always use Fraction (or integer basis points rate_ten_thousandths // 10000).
  • Applying the surcharge to the total purchase amount: Only credit_portion (after subtracting gift cards) incurs the regional surcharge.
  • Capping CC_REFUND at the pre-surcharge credit_portion: Credit-card refunds are capped at CC_CHARGE including the surcharge (e.g., 8400 in Example 2, not 8000).
  • 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 timestamp now == valid_before when 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 integer 125 (zero-padding to 4 decimal places) and compute (credit_portion * rate_bps) // 10000 with 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 to cc_charge) and remaining_total_refundable (initialized to amount + surcharge) per charge_id. On each partial refund, return cc_refund = min(refund_amount, remaining_cc_refundable) to the credit card, decrement remaining_cc_refundable by cc_refund, and issue the remainder gc_refund either onto a numbered card like REFUND_<charge_id>_<seq> or by adding balance to an existing REFUND_<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 .5 ties to the nearest even cent so upward and downward rounding cancel out over millions of transactions). Compute the exact rational value with Fraction or decimal.Decimal, apply the chosen rounding rule once to compute surcharge, and store that exact integer cc_charge so 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 = 12 might still have been valid for a late-arriving charge at t = 5, and spending at t = 5 changes what remains at t = 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

Similar questions

More Stripe interview questions

All 139 Stripe questions →