Amusement Park Tap-to-Ride: Credits, Surcharges, and Refunds
Data Structure DesignModel answerLast updated
Simulate a wristband payment system that drains expiring credits before a linked card, applies zone-based surcharges, and splits refunds back across both funding sources.
Amusement Park Tap-to-Ride: Credits, Surcharges, and Refunds
An amusement park lets guests load promotional ride credits onto their wristband — each credit balance has an expiry tick after which it becomes unusable. The wristband also has one linked payment card as a fallback. Your job is to implement the transaction engine that keeps every guest's balances accurate.
Function Signature
def process_events(events: list[str], zone_surcharges: list[str]) -> list[str]:
events is a time-ordered list of comma-separated records in one of three formats:
t,ADD_CREDIT,guest_id,card_id,amount,expires_at
t,RIDE,charge_id,guest_id,amount,zone_id
t,REFUND,charge_id,refund_amount
All monetary amounts are non-negative integers in cents. Each entry in zone_surcharges looks like "100-199:0.10", which means any ride whose zone_id falls in [100, 199] incurs a 10% surcharge on the portion billed to the linked card. Return one output string per input event, preserving order.
Event Rules
ADD_CREDIT — Adds or tops up a named credit balance for a guest. The credit is valid for any transaction where t < expires_at. Output: "".
RIDE — Charges the guest for a ride costing amount cents.
- Draw first from the guest's valid, unexpired credit balances (those with
balance > 0andt < expires_at). - Prioritize the balance expiring soonest; break ties by lexicographically smaller
card_id. - Any portion not covered by credits is billed to the linked card. The zone surcharge applies only to that card-billed portion; round half-cents up to the nearest whole cent.
- Output:
"{charge_id},{credit_used},{card_charged}".
REFUND — Returns up to refund_amount of the original pre-surcharge ticket price, capped at whatever hasn't already been refunded on this charge.
- Draw the refund first from the card-billed base amount (the pre-surcharge portion charged to the card), reversing the surcharge at the same rate.
- Any remaining refund beyond what was card-billed comes from the credit-paid portion and is returned as a brand-new, non-expiring store credit on the guest's wristband.
- Output:
"{charge_id},{card_refunded},{credit_refunded}".
Example
events = [
"1,ADD_CREDIT,G1,C1,2000,100",
"2,RIDE,R1,G1,5000,150",
"3,REFUND,R1,1800",
]
zone_surcharges = ["100-199:0.10", "200-299:0.05"]
process_events(events, zone_surcharges)
# -> ["", "R1,2000,3300", "R1,1980,0"]
For the RIDE at t=2: the 2000-cent credit (zone 150, expires at t=100) has already expired — wait, t=2 < expires_at=100, so it is still valid. The full 2000 credit is consumed, leaving 3000 on the card. Zone 150 falls in [100-199] at 10%, so card charge = 3000 × 1.10 = 3300.
For the REFUND of 1800: the card-billed base is 3000, none of it has been refunded yet. 1800 comes entirely from that base, reversed at 10%: 1800 × 1.10 = 1980 back to the card. Nothing spills into the credit bucket, so credit_refunded = 0.
Constraints
- Up to 10^5 total events.
zone_surchargescontains at most 100 non-overlapping ranges.- Every
REFUNDreferences acharge_idthat appeared in a priorRIDEevent. - Multiple
REFUNDevents may target the samecharge_id; the second one picks up where the first left off.
Hints
Hint 1
For each guest, think about what data structure keeps the 'soonest-expiring credit first' ordering efficient. You need to drain credits in that order on every RIDE.
Hint 2
The surcharge only applies to the card-billed portion, not the full ride price. Store the pre-surcharge card base and the rate separately per charge — you'll need them verbatim when computing refunds later.
Hint 3
On a REFUND, work bucket-by-bucket: first exhaust the unrefunded card-base (scaling the refund by 1+rate), then spill into the credit bucket and issue a fresh non-expiring balance. Track how much of the card-base has been refunded across multiple partial refunds.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a stateful simulation with three distinct event handlers. The key insight is to separate concerns cleanly: credit-draining logic for RIDE, zone-lookup for surcharges, and a two-bucket depletion model for REFUND.
State to maintain
- Wallets:
guest_id → {card_id → {balance, expires_at}}. A plain dict works; we sort at query time. - Charge ledger:
charge_id → {guest_id, amount, credit_paid, card_base, card_base_refunded, rate, refunded_ticket}. Everything needed for future refunds is recorded at the time of the RIDE so we never re-derive it.
RIDE handler
- Collect all credit cards for the guest where
balance > 0andt < expires_at. - Sort by
(expires_at, card_id)— earliest expiry first, lexicographic tie-break. - Greedily drain each card until the ride cost is covered or credits run out.
- The leftover is
card_base. Look up the surcharge rate with a linear scan over the at-most-100 ranges (fast enough). Computecard_charged = round_half_up(card_base * (1 + rate)). - Record everything in the charge ledger.
Why earliest-expiry first? It's the only ordering that avoids leaving a soon-to-expire balance sitting idle while a longer-lived one gets consumed. It's also the only ordering the problem specifies, so it must be followed exactly for deterministic output.
REFUND handler
The refund operates on the original ticket price (pre-surcharge), capped at what remains unrefunded. Work two buckets in order:
- Card bucket:
card_base_left = card_base - card_base_refunded. Takefrom_card_base = min(card_base_left, refund_amount)from this bucket. The actual money returned to the card isround_half_up(from_card_base * (1 + rate))— the surcharge is reversed. - Credit bucket: the remainder
from_credit = refund_amount - from_card_baseis returned as a new non-expiring store-credit card. Assign it a fresh unique ID (e.g.,RFND1,RFND2, …) and add it to the guest's wallet withexpires_at = infinity.
Advance card_base_refunded and refunded_ticket so subsequent refunds pick up from the right position.
Common mistake: applying the surcharge to the full refund amount rather than just the card-base portion, or forgetting to track card_base_refunded separately from refunded_ticket, causing the second partial refund to miscalculate the bucket split.
Rounding
Use "round half up": floor(x + 0.5) for non-negative values. Python's built-in round() uses banker's rounding (round half to even), which gives wrong results on exactly half-cent amounts.
Complexity
- Time: O(E · C log C) where C is the max number of credit cards a single guest accumulates. In practice C is small. Zone lookup is O(Z) per RIDE with Z ≤ 100. Overall effectively O(E log E).
- Space: O(E) for the ledger and wallets.
Full implementation
import math
def _round_half_up(x: float) -> int:
"""Round a non-negative float number of cents to the nearest integer, half up."""
return math.floor(x + 0.5)
def process_events(events: list[str], zone_surcharges: list[str]) -> list[str]:
# Parse zone surcharge ranges once up front
ranges: list[tuple[int, int, float]] = []
for spec in zone_surcharges:
zone_part, rate_part = spec.split(":")
lo, hi = zone_part.split("-")
ranges.append((int(lo), int(hi), float(rate_part)))
def rate_for_zone(zone_id: int) -> float:
for lo, hi, rate in ranges:
if lo <= zone_id <= hi:
return rate
return 0.0
# guest_id -> card_id -> {"balance": int, "expires_at": int | float}
wallets: dict[str, dict[str, dict]] = {}
# charge_id -> ledger record
charges: dict[str, dict] = {}
refund_counter = 0
output: list[str] = []
for line in events:
parts = line.split(",")
t = int(parts[0])
kind = parts[1]
if kind == "ADD_CREDIT":
# t,ADD_CREDIT,guest_id,card_id,amount,expires_at
guest_id, card_id, amount, expires_at = parts[2], parts[3], parts[4], parts[5]
wallets.setdefault(guest_id, {})[card_id] = {
"balance": int(amount),
"expires_at": int(expires_at),
}
output.append("")
elif kind == "RIDE":
# t,RIDE,charge_id,guest_id,amount,zone_id
charge_id, guest_id, amount, zone_id = parts[2], parts[3], int(parts[4]), int(parts[5])
wallet = wallets.get(guest_id, {})
# Collect usable (non-expired, non-empty) credit cards
usable = sorted(
((card["expires_at"], cid) for cid, card in wallet.items()
if card["balance"] > 0 and t < card["expires_at"])
)
remaining = amount
for _, cid in usable:
if remaining == 0:
break
card = wallet[cid]
draw = min(card["balance"], remaining)
card["balance"] -= draw
remaining -= draw
credit_used = amount - remaining
card_base = remaining
rate = rate_for_zone(zone_id) if card_base > 0 else 0.0
card_charged = _round_half_up(card_base * (1 + rate)) if card_base > 0 else 0
charges[charge_id] = {
"guest_id": guest_id,
"amount": amount, # original pre-surcharge ticket price
"credit_paid": credit_used,
"card_base": card_base, # pre-surcharge card portion
"card_base_refunded": 0, # how much of card_base has been refund-reversed
"rate": rate,
"refunded_ticket": 0, # total ticket cents refunded so far
}
output.append(f"{charge_id},{credit_used},{card_charged}")
elif kind == "REFUND":
# t,REFUND,charge_id,refund_amount
charge_id, refund_amount = parts[2], int(parts[3])
rec = charges[charge_id]
# Cap at what's still refundable on the ticket price
refund_amount = min(refund_amount, rec["amount"] - rec["refunded_ticket"])
# Bucket 1: reverse card-billed base
card_base_left = rec["card_base"] - rec["card_base_refunded"]
from_card_base = min(card_base_left, refund_amount)
card_refunded = _round_half_up(from_card_base * (1 + rec["rate"])) if from_card_base > 0 else 0
# Bucket 2: anything left comes from the credit-paid portion
from_credit = refund_amount - from_card_base
credit_refunded = from_credit
# Advance ledger
rec["card_base_refunded"] += from_card_base
rec["refunded_ticket"] += refund_amount
# Issue a new non-expiring store credit if needed
if from_credit > 0:
refund_counter += 1
new_card_id = f"RFND{refund_counter}"
wallets.setdefault(rec["guest_id"], {})[new_card_id] = {
"balance": from_credit,
"expires_at": math.inf, # never expires
}
output.append(f"{charge_id},{card_refunded},{credit_refunded}")
else:
raise ValueError(f"Unknown event type: {kind}")
return output
Edge cases to verify
- Ride fully covered by credits:
card_base = 0, no surcharge is computed,card_charged = 0. - Card expired before the ride: excluded from
usableeven if balance > 0 — thet < expires_atguard handles this. - Multiple partial refunds: the second REFUND sees a reduced
card_base_left, potentially spilling into the credit bucket even if the first refund did not. - Refund on a ride with zero card charge:
card_base = 0, so the entire refund goes to the credit bucket immediately.