Simulate a Stateful Banking Ledger with Queued Payments
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate an in-memory banking system handling accounts, balances, scheduled payments via a priority queue, and account merges.
Implement a simulation function run_bank_system that processes a sequence of timestamped operations for an in-memory financial ledger.
Every operation carries an integer timestamp t. Timestamps across calls are non-decreasing. Before carrying out the operation at time t, the ledger must first execute all queued scheduled payments whose scheduled trigger time is less than or equal to t.
Scheduled Payment Execution Order & Rules
- Process due payments in ascending order of scheduled execution time (
timestamp + delay). - If multiple payments have the exact same execution time, resolve ties alphabetically (lexicographically) by their payment identifier string
payment_id. - To execute a payment, verify:
- Both the current source account and current destination account are active.
- The current source account ID is distinct from the current destination account ID.
- The current source account has a balance $\ge$ payment amount.
- If valid, deduct the amount from the source, add it to the destination, and increase the source's cumulative lifetime outgoing spending counter by
amount. Mark the payment as completed. - If invalid (e.g. insufficient funds, deactivated account, or source and target became identical), the payment fails silently and is permanently discarded (marked as completed without transferring funds).
- A scheduled payment processes at most once.
Operations
Each operation is represented by a command string in operations and a matching parameter list in arguments (where args[0] is always timestamp):
-
"create_account":[timestamp, account_id]- Registers a new active account with balance
0and spending0. - Returns
Trueif created. ReturnsFalseifaccount_idis currently an active account.
- Registers a new active account with balance
-
"deposit":[timestamp, account_id, amount]- Adds
amounttoaccount_id. - Returns the updated integer balance, or
Noneifaccount_idis not active.
- Adds
-
"transfer":[timestamp, src_id, dest_id, amount]- Immediately transfers
amountfromsrc_idtodest_id. - Succeeds if both accounts are active,
src_id != dest_id, andsrc_id's balance is $\ge$amount. - On success, increases
src_id's cumulative outgoing spending byamountand returnsTrue. Otherwise returnsFalse.
- Immediately transfers
-
"top_spenders":[timestamp, n]- Returns a list of up to
nactive account IDs sorted by total cumulative outgoing transfer spending in descending order. - Ties in spending are broken alphabetically by
account_id. - If
n <= 0, returns[]. Accounts with zero spending are included if space permits.
- Returns a list of up to
-
"schedule_payment":[timestamp, payment_id, src_id, dest_id, amount, delay]- Schedules a future transfer to execute at
timestamp + delay. - Returns
Trueifpayment_idhas never been used before, bothsrc_idanddest_idare currently active,src_id != dest_id, andamount > 0. ReturnsFalseotherwise.
- Schedules a future transfer to execute at
-
"cancel_payment":[timestamp, payment_id]- Cancels a pending scheduled payment.
- Returns
Trueifpayment_idexists and is currently pending. ReturnsFalseif it does not exist, was already cancelled, or already executed.
-
"merge_accounts":[timestamp, target_id, source_id]- Merges
source_idintotarget_id. - Succeeds only if both
target_idandsource_idare active andtarget_id != source_id. ReturnsFalseif invalid. - On success:
- Transfers all current balance and lifetime spending from
source_idintotarget_id. - Updates all pending scheduled payments where
source_idappears as source or destination so they point totarget_idinstead. - Deactivates
source_id(it can later be re-created via"create_account"as a fresh account). - Returns
True.
- Transfers all current balance and lifetime spending from
- Merges
Constraints
- $1 \le \text{timestamp} \le 10^9$, non-decreasing across sequence.
- $1 \le \text{amount}, \text{delay} \le 10^9$.
- Account and payment IDs are non-empty strings of alphanumeric characters ($\le 32$ chars).
- Total operation count $\le 10^4$.
Examples
Example 1
Input: run_bank_system(['create_account', 'create_account', 'deposit', 'schedule_payment', 'transfer', 'top_spenders', 'deposit', 'top_spenders'], [[1, 'A'], [1, 'B'], [2, 'A', 100], [3, 'p1', 'A', 'B', 40, 5], [4, 'A', 'B', 20], [5, 2], [8, 'B', 10], [9, 1]])
Output: [True, True, 100, True, True, ['A', 'B'], 70, ['A']]
Hints
Hint 1
Flush all scheduled payments with execution_time <= current timestamp before handling the current command.
Hint 2
Maintain a min-heap storing tuples of (execution_time, payment_id) for scheduled tasks to efficiently retrieve due payments in order.
Hint 3
Use a status flag ('pending', 'cancelled', 'finished') for each payment to easily handle cancellations without needing to delete elements from middle of the min-heap.
Hint 4
When merging accounts, rewrite the source and destination fields of all currently pending payments.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating a stateful banking ledger with event scheduling and lazy queue flushing.
- Scheduled Payments Heap: Maintain a min-heap storing
(execution_time, payment_id). Because Python compares tuples element-by-element, ordering byexecution_timefirst andpayment_idsecond automatically satisfies the primary sorting and tie-breaking requirements. - Flush On Each Command: Prior to evaluating any operation at time
t, pop all items from the min-heap withexecution_time <= t. - Lazy Cancellation: Cancelling a scheduled payment sets its status field in a dictionary to
"cancelled". When popped during a flush, any non-pendingitem is simply ignored. - Account Merges: When
sourcemerges intotarget, we immediately transfersource's balance and spending totarget, iterate through all pending scheduled payments to replace references tosourcewithtarget, and removesourcefrom the set of active accounts. - Top Spenders: Collect all active accounts and sort them primarily by
-spending[acc]and secondarily byacclexicographically. Take the firstnaccounts.
Complexity
- Scheduled Flushing: Amortized $O(\log P)$ per scheduled payment, where $P$ is the total number of payments ever scheduled.
- Account Operations (
create,deposit,transfer,cancel): $O(1)$ average time. - Merge Operation: $O(P)$ to update references across pending payments.
- Top Spenders: $O(A \log A)$ where $A$ is the number of currently active accounts.
- Space Complexity: $O(A + P)$ memory to track account state and scheduled events.
Reference Solution
import heapq
from typing import List
def run_bank_system(operations: List[str], arguments: List[List]) -> List[object]:
balances = {}
spending = {}
active = set()
payments = {}
events = []
results = []
def process(timestamp):
while events and events[0][0] <= timestamp:
execution_time, payment_id = heapq.heappop(events)
payment = payments[payment_id]
if payment["status"] != "pending":
continue
payment["status"] = "finished"
src, dest, amount = payment["src"], payment["dest"], payment["amount"]
if src in active and dest in active and src != dest and balances[src] >= amount:
balances[src] -= amount
balances[dest] += amount
spending[src] += amount
for operation, args in zip(operations, arguments):
timestamp = args[0]
process(timestamp)
if operation == "create_account":
_, account_id = args
if account_id in active:
results.append(False)
else:
active.add(account_id)
balances[account_id] = 0
spending[account_id] = 0
results.append(True)
elif operation == "deposit":
_, account_id, amount = args
if account_id not in active:
results.append(None)
else:
balances[account_id] += amount
results.append(balances[account_id])
elif operation == "transfer":
_, src, dest, amount = args
if src not in active or dest not in active or src == dest or balances[src] < amount:
results.append(False)
else:
balances[src] -= amount
balances[dest] += amount
spending[src] += amount
results.append(True)
elif operation == "top_spenders":
_, n = args
ordered = sorted(active, key=lambda acc: (-spending[acc], acc))
results.append(ordered[:max(0, n)])
elif operation == "schedule_payment":
_, payment_id, src, dest, amount, delay = args
if (payment_id in payments or src not in active or dest not in active
or src == dest or amount <= 0):
results.append(False)
else:
execution_time = timestamp + delay
payments[payment_id] = {
"src": src, "dest": dest, "amount": amount, "status": "pending"
}
heapq.heappush(events, (execution_time, payment_id))
results.append(True)
elif operation == "cancel_payment":
_, payment_id = args
payment = payments.get(payment_id)
if payment is None or payment["status"] != "pending":
results.append(False)
else:
payment["status"] = "cancelled"
results.append(True)
elif operation == "merge_accounts":
_, target, source = args
if target not in active or source not in active or target == source:
results.append(False)
else:
balances[target] += balances[source]
spending[target] += spending[source]
for payment in payments.values():
if payment["status"] == "pending":
if payment["src"] == source:
payment["src"] = target
if payment["dest"] == source:
payment["dest"] = target
active.remove(source)
results.append(True)
else:
raise ValueError("Unknown operation: " + operation)
return results