KatInterview

Gift Card Waterfall, ZIP Surcharges and Refund Credits

Heaps, Sorting & SearchAuto-graded · 22 test cases
HardAuto-gradedHeaps, Sorting & Searchsimulationheappriority-queue

Last 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_GIFTCARD gives customer customer_id a new card card_id with starting balance amount. 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_GIFTCARD is the empty string "".

  • A CHARGE of amount is 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 CHARGE is the final credit card amount followed by one ,card_id:amount_used item for each card that contributed a positive amount:

    CC_CHARGE,GIFT_CARD_ID_1:AMOUNT_USED,GIFT_CARD_ID_2:AMOUNT_USED
    

    Items appear in ascending card_id order, 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_CHARGE includes the surcharge described below.

Expiry and priority

  • A card made by ADD_GIFTCARD is valid at time T only when T < valid_before. When T >= valid_before it is expired and its leftover balance is gone permanently.
  • Cards created by refunds (see below) never expire. Since every ADD_GIFTCARD line has a valid_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 at T and have a positive balance. They are consumed in this order:
    1. cards with an expiry, earliest valid_before first;
    2. then cards without an expiry;
    3. cards sharing the same expiry (including any two non-expiring cards) are ordered by ascending card_id.

ZIP surcharges

  • Find the range in surcharge_table containing the charge's zip_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 of 10000 at rate 0.05 yields CC_CHARGE = 10500.
  • The exact value of credit_card_portion * rate is 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_REFUND is the smaller of refund_amount and the CC_CHARGE that 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, with card_id equal to REFUND_ plus the charge id (for chg_1, REFUND_chg_1), balance GC_REFUND, and no expiry. It then behaves like any other card in later charges. If GC_REFUND is 0, no card is created.
  • A refund never restores balance to the gift cards used by the original charge.
  • The output for a REFUND is CC_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^4 and 0 <= len(surcharge_table) <= 1000.
  • All lines are well formed. Timestamps are integers in [0, 10^9] and never decrease along events; 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^8 in ADD_GIFTCARD and CHARGE lines.
  • customer_id, card_id and charge_id are 1 to 20 characters of ASCII letters, digits and underscores. card_id values in ADD_GIFTCARD lines are unique and never begin with REFUND_. charge_id values are unique among CHARGE lines.
  • zip_code is exactly five digits and may have leading zeros. Each range has five-digit bounds with start_zip <= end_zip, and ranges never overlap.
  • Each rate is a decimal with at most 4 digits after the point, in [0, 1].
  • Every REFUND refers to a CHARGE appearing earlier, and each charge is refunded at most once. refund_amount >= 1 and is at most what was originally paid for that charge (its amount plus its surcharge).
  • Every output amount is at most 2 * 10^8. A customer's total balance across cards may exceed 2^31 - 1 but stays below 2^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.