Ride-Share Wallet: Credit Vouchers, Zone Surcharges, and Refunds
Data Structure DesignModel answerLast updated
Simulate a ride-share payment ledger that drains expiring vouchers in priority order, applies zone-based surcharges to card charges, and splits refunds between card and new store credit.
Ride-Share Wallet Ledger
A ride-share platform lets passengers pay for trips using ride credits (prepaid, promotional balances that expire) combined with a linked payment card for any shortfall. You need to build the ledger engine that processes a time-ordered stream of wallet events and produces one output line per event.
def process_ledger(events: list[str], surcharge_bands: list[str]) -> list[str]:
Event format
Each event is a |-delimited string. Timestamps are non-decreasing integers.
t|LOAD|rider|credit_id|amount|expires_at
t|TRIP|trip_id|rider|amount|zone
t|CANCEL|trip_id|amount
Each entry in surcharge_bands has the form lo-hi:bps. A trip whose integer zone falls in [lo, hi] incurs a surcharge of bps basis points (1 bps = 0.01 %) applied to the card portion only. All monetary values are integer cents.
Part 1 — Loading credits and paying for trips
A LOAD event adds a credit balance to a rider's wallet and outputs:
t LOAD <credit_id> <amount>
A TRIP event pays from the rider's available credits first, then puts any remainder on the card. Output:
t TRIP <trip_id> credits=<V> card=<C> surcharge=<S> charged=<C+S>
Part 2 — Expiry and spend priority
A credit is spendable only when t < expires_at (strictly less than). Spend credits in order of earliest expires_at first. Break ties by lexicographically smaller credit_id. A credit may be partially spent and retains its remaining balance.
Part 3 — Zone surcharges
S = round_half_up(C * bps / 10000)
Compute this with integer arithmetic only. When multiple bands cover the same zone, the first band listed in surcharge_bands applies. If no band matches, S = 0.
Part 4 — Cancellations and partial refunds
A CANCEL event returns money for a previous trip:
- Refund the card first, up to the card portion not yet refunded. Surcharges are never refunded.
- Any remainder is returned as a new credit for the same rider, up to the credit portion not yet refunded. The new credit's id is
RF-<trip_id>-<k>, wherekis the running refund count for that trip including this one. It expires att + 90. - Output
t CANCEL <trip_id> card=<X> credit=<Y>, appendingvoucher=<id>whenY > 0. - If the trip is unknown, or the requested amount exceeds what is still refundable, output
t CANCEL <trip_id> REJECTEDand change nothing.
Example
surcharge_bands = ["4000-4999:250", "9000-9499:175", "9100-9199:999"]
events:
10|LOAD|mia|c-b|1500|200
12|LOAD|mia|c-a|800|200
15|LOAD|mia|c-c|1000|50
20|TRIP|t1|mia|2000|4410
60|TRIP|t2|mia|3000|9120
70|CANCEL|t2|1500
75|TRIP|t3|mia|900|1000
80|CANCEL|t2|800
81|CANCEL|t9|100
100|TRIP|t4|mia|700|4000
110|CANCEL|t1|2500
Expected output:
10 LOAD c-b 1500
12 LOAD c-a 800
15 LOAD c-c 1000
20 TRIP t1 credits=2000 card=0 surcharge=0 charged=0
60 TRIP t2 credits=1300 card=1700 surcharge=30 charged=1730
70 CANCEL t2 card=1500 credit=0
75 TRIP t3 credits=0 card=900 surcharge=0 charged=900
80 CANCEL t2 card=200 credit=600 voucher=RF-t2-2
81 CANCEL t9 REJECTED
100 TRIP t4 credits=600 card=100 surcharge=3 charged=103
110 CANCEL t1 REJECTED
Walkthrough highlights:
t=20:c-cexpires soonest (at 50), spent first. Thenc-abeatsc-bon the id tie-break. Total 1500 + 500 = 2000 from credits, card = 0.t=60: zone 9120 matches both the 175 bps and 999 bps bands — first listed (175 bps) wins.round_half_up(1700 × 175 / 10000)=round_half_up(29.75)= 30.t=80: second refund ont2;k=2so new credit id isRF-t2-2.t=100: theRF-t2-2credit (600 cents, expires at 80+90=170) is now available and covers 600. Card base = 100;round_half_up(100 × 250 / 10000)=round_half_up(2.5)= 3.t=110: only 0 card and 0 credits remain refundable ont1→ REJECTED.
Constraints
- Up to 10⁵ events total.
- All amounts are positive integers up to 10⁹ cents.
- All
credit_idandtrip_idvalues are unique strings; preserve them exactly (do not normalise).
Hints
Hint 1
Model wallet state as a dict of credits per rider, each storing [balance, expires_at]. Sort usable credits by (expires_at, credit_id) before each trip — Python tuple ordering handles the tie-break for free.
Hint 2
Use only integer arithmetic for the surcharge: `(C * bps + 5000) // 10000` gives round-half-up without floating point. Float multiplication like `C * 0.0175` can produce values like 29.4999... in binary and round the wrong way.
Hint 3
For refunds, store card_left and credit_left per order as mutable counters. Always validate before mutating: reject first if amount > card_left + credit_left, then apply card-first logic and mint a new credit only if the credit portion is positive.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a rule-following simulation. The challenge is not algorithmic cleverness — it is precise state tracking, correct priority ordering, and integer-only money math. Build it in layers matching the four parts, verifying the example after each one.
State design
credits[rider][credit_id] = [balance, expires_at]
orders[trip_id] = {
rider: str,
card_left: int, # card amount still refundable
credit_left: int, # credit amount still refundable
refund_count: int # how many CANCELs have hit this order
}
Both structures are plain dicts. No exotic containers needed until you care about large-R performance (discussed at the end).
Key rules and their pitfalls
Expiry is strict. A credit expiring at timestamp 50 is not usable at t=50. Check t < expires_at, not <=.
Priority sort. Gather credits where balance > 0 and t < expires_at, then sort by (expires_at, credit_id). Python's default tuple comparison handles the lexicographic tie-break correctly. Do not sort the surcharge bands — first match wins in original order.
Round-half-up with integers. The formula (C * bps + 5000) // 10000 is the only correct approach. Adding half the divisor before floor-dividing implements round-half-up exactly. Never compute C * bps / 10000 as a float: binary floating point can represent 29.75 as 29.749999... and produce the wrong result.
Refund validation before mutation. Check amount > card_left + credit_left first. If it fails, output REJECTED and continue — touch nothing. This prevents partial state corruption.
Refund credit id counter increments only on success. A rejected CANCEL does not bump refund_count.
Refund credits are ordinary credits. Once minted, RF-t2-2 participates in the same priority queue as any other credit. There is nothing special to handle.
Reference implementation
from collections import defaultdict
REFUND_TTL = 90
def parse_bands(surcharge_bands):
result = []
for entry in surcharge_bands:
rng, bps = entry.split(":")
lo, hi = rng.split("-")
result.append((int(lo), int(hi), int(bps)))
return result
def compute_surcharge(card_base, zone, bands):
for lo, hi, bps in bands: # first match wins; do not sort
if lo <= zone <= hi:
return (card_base * bps + 5000) // 10000 # round half up
return 0
def process_ledger(events, surcharge_bands):
bands = parse_bands(surcharge_bands)
credits = defaultdict(dict) # rider -> {credit_id: [balance, expires_at]}
orders = {} # trip_id -> order record
out = []
for line in events:
parts = line.split("|")
t, kind = int(parts[0]), parts[1]
if kind == "LOAD":
rider, cid, amount, exp = parts[2], parts[3], int(parts[4]), int(parts[5])
credits[rider][cid] = [amount, exp]
out.append(f"{t} LOAD {cid} {amount}")
elif kind == "TRIP":
trip_id, rider, amount, zone = parts[2], parts[3], int(parts[4]), int(parts[5])
# Gather and sort usable credits
usable = sorted(
(exp, cid)
for cid, (bal, exp) in credits[rider].items()
if bal > 0 and t < exp
)
remaining = amount
for exp, cid in usable:
if remaining == 0:
break
take = min(remaining, credits[rider][cid][0])
credits[rider][cid][0] -= take
remaining -= take
from_credits = amount - remaining
card_base = remaining
surcharge = compute_surcharge(card_base, zone, bands)
orders[trip_id] = {
"rider": rider,
"card_left": card_base,
"credit_left": from_credits,
"refund_count": 0,
}
out.append(
f"{t} TRIP {trip_id} credits={from_credits} card={card_base} "
f"surcharge={surcharge} charged={card_base + surcharge}"
)
elif kind == "CANCEL":
trip_id, amount = parts[2], int(parts[3])
o = orders.get(trip_id)
if o is None or amount > o["card_left"] + o["credit_left"]:
out.append(f"{t} CANCEL {trip_id} REJECTED")
continue
to_card = min(amount, o["card_left"])
to_credit = amount - to_card
o["card_left"] -= to_card
o["credit_left"] -= to_credit
o["refund_count"] += 1
result = f"{t} CANCEL {trip_id} card={to_card} credit={to_credit}"
if to_credit > 0:
new_cid = f"RF-{trip_id}-{o['refund_count']}"
credits[o["rider"]][new_cid] = [to_credit, t + REFUND_TTL]
result += f" voucher={new_cid}"
out.append(result)
else:
raise ValueError(f"unrecognised event kind: {kind}")
return out
Complexity
| Operation | Cost |
|---|---|
| LOAD | O(1) |
| TRIP | O(R log R) where R = rider's current credit count |
| CANCEL | O(1) |
The sort inside TRIP dominates. If R can be large (many refund credits accumulate over time), replace the per-rider dict with a min-heap keyed by (expires_at, credit_id). Pop lazily: skip entries whose balance has dropped to zero or that have expired. This brings each voucher consumption to O(log R) amortised. Overall time complexity is O(N log R) for N events.
Memory is O(total credits issued + total orders), both bounded by the event count.
Common mistakes
- Float surcharge math. Always use the
(C * bps + 5000) // 10000pattern. - Mutating state before validating a CANCEL. Validate the full amount first, then apply changes atomically.
- Treating expiry as
<=instead of<. Re-read the spec: the credit is dead at the moment it expires. - Sorting surcharge bands. The first-listed rule is intentional (it lets operators override a broad band with a narrow one). Sorting by range size would silently break this.
- Normalising ids. If a trip id is
007, keep it as"007". Useint()only for numeric fields, not for id strings. - Forgetting that
konly increments on success. A rejected CANCEL must not changerefund_count, otherwise the next successful refund gets the wrong id.