Funding Ledger with Rail-Specific Settlement and Window Caps
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate an ordered account ledger where each payment rail has its own settlement delay, cutoff-shifted window assignment, and per-window cap, and output the combined results.
Funding Ledger
A fundraising platform lets members receive money into accounts through three payment rails: CARD, ACH and WIRE. Rails differ in how long money takes to become available, which accounting window a deposit is charged to, and how much one account may receive per window.
Write run_funding_ledger(events), which handles a list of events strictly in the given order and returns a single string.
Events
Each event is a list whose first element is its type and whose second element is tick, the current time when the event runs. Ticks never decrease from one event to the next.
["INIT", tick, account_id]creates a new account with nothing accepted and nothing settled.- If
account_idalready exists, the result is"ERROR". - Otherwise the event succeeds and produces no output.
- If
["DEPOSIT", tick, account_id, rail, cents]tries to addcentsto the account throughrail.- If the account does not exist, the result is
"ERROR". - Let
Wbe the window for this tick on this rail (see below). If the amount already accepted for this(account, rail, W)pluscentswould be greater than the rail's limit, the result is"REJECTED". A rejected deposit changes nothing at all. - Otherwise the result is
"ACCEPTED". The amount is added to the(account, rail, W)usage and to the account's accepted total immediately, and it becomes settled at ticktick + settlement_delay.
- If the account does not exist, the result is
["QUERY", tick, account_id]reports the account's balances as"{settled}/{accepted}".acceptedis the sum of all accepted deposits, whether or not they have settled.settledis the sum of accepted deposits whose settlement tick is less than or equal to the query's tick.- If the account does not exist, the result is
"ERROR".
Settlement is judged against the tick of the event being processed. A deposit with delay 0 is therefore already settled for any later event at the same tick.
Rail table
| Rail | settlement_delay | cutoff | window_length | limit_cents (per account, per window) |
|---|---|---|---|---|
| CARD | 0 | 24 | 24 | 20000 |
| ACH | 3 | 17 | 24 | 5000 |
| WIRE | 1 | 12 | 24 | 500000 |
Window assignment
For a rail and a tick, start with tick // window_length. If tick % window_length is greater than or equal to the rail's cutoff, the deposit belongs to the following window, so add 1. Limits are tracked separately for every combination of account, rail and window.
Output
Collect the results of all events that produce output (ERROR, ACCEPTED, REJECTED, and every query result) in event order and join them with commas. If nothing produces output, return an empty string.
Constraints
- Up to 100,000 events and up to 10,000 distinct accounts.
- All amounts fit in a 64-bit integer. Use integer arithmetic only.
- A rejected deposit must not affect window usage, the accepted total, or any pending settlement.
- Rail names in deposits are always one of
CARD,ACH,WIRE.
Examples
Example 1
Input: run_funding_ledger([['INIT', 0, 'alice'], ['DEPOSIT', 1, 'alice', 'CARD', 1000], ['DEPOSIT', 2, 'alice', 'ACH', 2000], ['QUERY', 3, 'alice'], ['QUERY', 5, 'alice'], ['DEPOSIT', 6, 'alice', 'ACH', 4500], ['QUERY', 6, 'alice']])
Output: 'ACCEPTED,ACCEPTED,1000/3000,3000/3000,REJECTED,3000/3000'
Hints
Hint 1
Keep the rail rules in a lookup table keyed by rail name, then compute the window number from the tick with divmod and the cutoff comparison.
Hint 2
Track window usage in a dictionary keyed by (account, rail, window) so that different rails and different windows never share a limit.
Hint 3
Accepted money should be added to the accepted total at once, but to the settled total only later. Put (settle_tick, account, cents) into a min-heap and pop everything due before handling each event.
Hint 4
Remember that a successful INIT adds nothing to the output, and a rejected deposit must leave every counter untouched.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The ledger is a straightforward simulation. Three pieces of state are needed:
- Account totals. For each account, keep
settledandacceptedamounts. - Window usage. A dictionary keyed by
(account, rail, window)stores how much has been accepted there. A deposit is rejected whenused + centsexceeds the rail's limit. Because the key includes the rail, rails never share a cap. - Pending settlements. A min-heap of
(settle_tick, account, cents). Before handling each event, pop every entry whosesettle_tick <= tickand add its amount to that account'ssettledtotal. Since ticks never decrease, the settled totals are always correct at the moment an event is evaluated.
The window number is tick // 24, plus one when tick % 24 >= cutoff. The comparison must be >=, so a tick exactly at the cutoff already counts toward the next window. For CARD the cutoff is 24, which a time-of-day can never reach, so card deposits always stay in their own day.
Successful INIT events add nothing to the output. A rejected deposit returns before touching usage, totals or the heap, so it leaves no trace.
Why it is correct
Every accepted deposit is charged to exactly one window and one rail, so the limit check sees exactly the amounts accepted earlier in that bucket. Each accepted deposit is pushed to the heap exactly once, and it is moved to settled the first time an event arrives at a tick at or after its settlement tick. That matches the definition of settled funds. Events are processed in input order, so the outputs come out in the required order.
Complexity
Each event costs O(log P) for heap operations, where P is the number of pending deposits, and each deposit is pushed and popped once. Total time is O(N log N) for N events. Space is O(N) for the heap and window usage plus O(A) for A accounts.
Reference solution
import heapq
from typing import List
RAIL_TABLE = {
"CARD": {"delay": 0, "cutoff": 24, "window_length": 24, "limit": 20000},
"ACH": {"delay": 3, "cutoff": 17, "window_length": 24, "limit": 5000},
"WIRE": {"delay": 1, "cutoff": 12, "window_length": 24, "limit": 500000},
}
def run_funding_ledger(events: List[List]) -> str:
accounts = {} # account_id -> [settled, accepted]
usage = {} # (account_id, rail, window) -> cents accepted
pending = [] # heap of (settle_tick, account_id, cents)
out = []
for ev in events:
kind, tick = ev[0], ev[1]
# Settle everything that is due by this tick.
while pending and pending[0][0] <= tick:
_, acc, cents = heapq.heappop(pending)
accounts[acc][0] += cents
if kind == "INIT":
acc = ev[2]
if acc in accounts:
out.append("ERROR")
else:
accounts[acc] = [0, 0]
elif kind == "DEPOSIT":
acc, rail, cents = ev[2], ev[3], ev[4]
if acc not in accounts:
out.append("ERROR")
continue
rule = RAIL_TABLE[rail]
window, tod = divmod(tick, rule["window_length"])
if tod >= rule["cutoff"]:
window += 1
key = (acc, rail, window)
used = usage.get(key, 0)
if used + cents > rule["limit"]:
out.append("REJECTED")
continue
usage[key] = used + cents
accounts[acc][1] += cents
heapq.heappush(pending, (tick + rule["delay"], acc, cents))
out.append("ACCEPTED")
else: # QUERY
acc = ev[2]
if acc not in accounts:
out.append("ERROR")
else:
settled, accepted = accounts[acc]
out.append(f"{settled}/{accepted}")
return ",".join(out)