Ledger Simulator with Holds, Deferred Payments and Cancellations
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a small in-memory bank driven by a command script, covering account creation, instant and deferred transfers, batch settlement and cancellation of pending transfers.
Ledger Simulator
You are given a script for a tiny in-memory bank. The script is two parallel lists: commands[i] is the name of the i-th command, and params[i] is the list of arguments for that command. Run the commands in order and return a list with one result per command, in the same order.
State
- Every account is identified by a string user ID and holds an integer balance. A new account starts with a balance of
0. There is no deposit command. - Deferred transfers are tracked in a record. Each record stores the sender, the recipient, the amount and a status that is one of
pending,completedordeleted. - Deferred transfer IDs are strings of the form
"transfer-1","transfer-2", and so on. The counter starts at 1 and increases by one only each time a deferred transfer is successfully created.
Commands
create_user, with params = [user_id]
- If the ID is already in use, return
Falseand change nothing. - Otherwise create the account with balance
0and returnTrue.
get_balance, with params = [user_id]
- Return the user's current balance, or
Noneif the user does not exist. - Funds held by a pending deferred transfer are not part of the sender's balance (see
offline_transfer).
transfer, with params = [from_id, to_id, amount]
- The transfer is invalid if any of these holds:
- either user does not exist
from_id == to_idamount <= 0- the sender's balance is less than
amount
- If it is invalid, return
Falseand change nothing. - Otherwise move
amountfrom the sender to the recipient right away and returnTrue.
offline_transfer, with params = [from_id, to_id, amount]
- It is invalid under exactly the same rules as
transfer. If invalid, returnFalseand change nothing. - Otherwise subtract
amountfrom the sender's balance immediately (the money is held), do not credit the recipient yet, create apendingrecord, and return the new transfer ID string.
process_offline_transfers, with params = []
- Settle every
pendingrecord, in the order the records were created: add its amount to the recipient's balance and mark itcompleted. - Return the number of records settled in this call (an integer, possibly
0).
delete_transfer, with params = [transfer_id]
- If no record has that ID, or the record is not
pending(alreadycompletedordeleted), returnFalseand change nothing. - Otherwise give the held amount back to the sender, mark the record
deleted, and returnTrue. A deleted record can never be settled later.
Any other command name returns False and changes nothing.
Task
Implement run_bank_script(commands, params) that executes the script and returns the list of results.
Constraints
len(commands) == len(params).- User IDs and transfer IDs are strings; amounts are integers.
- Result types are exactly as above: booleans, integers, strings, or
None. - Money is conserved: total balances plus pending holds never change except through the commands above.
- Performance is not the focus; a straightforward simulation is enough.
Examples
Example 1
Input: run_bank_script(['create_user', 'create_user', 'transfer', 'get_balance', 'offline_transfer', 'get_balance', 'process_offline_transfers', 'get_balance', 'delete_transfer'], [['alice'], ['bob'], ['alice', 'bob', 30], ['alice'], ['alice', 'bob', 20], ['alice'], [], ['bob'], ['transfer-1']])
Output: [True, True, False, 0, False, 0, 0, 0, False]
Example 2
Input: run_bank_script(['create_user', 'create_user', 'offline_transfer', 'delete_transfer', 'get_balance', 'process_offline_transfers'], [['a'], ['b'], ['a', 'b', 10], ['transfer-1'], ['a'], []])
Output: [True, True, False, False, 0, 0]
Hints
Hint 1
Keep two dictionaries: one mapping user ID to balance, and one mapping transfer ID to a record holding sender, recipient, amount and status. Python dicts preserve insertion order, which gives you creation order for settlement.
Hint 2
Write one validity check and use it for both transfer and offline_transfer. Validate everything first and only mutate state after all checks pass, so a failure never leaves a partial change.
Hint 3
For offline_transfer, take the money from the sender at creation time. Settling then only credits the recipient, and deleting only refunds the sender, so only pending records may be settled or deleted. Increase the ID counter only on success.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a direct simulation. We keep two pieces of state:
balances: a dict from user ID to integer balance.records: a dict from transfer ID to a record with sender, recipient, amount and status. Because Python dicts keep insertion order, iterating overrecordsvisits transfers in creation order, which is the order required for settlement.
Each command is handled as follows:
- create_user: fail if the ID exists, otherwise add it with balance 0.
- get_balance: a dict lookup that returns
Nonefor unknown users. - transfer / offline_transfer: both share one validity check (both users exist, they differ, the amount is positive, the sender can afford it). All checks run before any mutation, so a failure changes nothing. An immediate transfer moves money at once. An offline transfer removes the money from the sender, stores a
pendingrecord, and returns a fresh ID. The counter only advances on success. - process_offline_transfers: credit the recipient of every
pendingrecord, mark itcompleted, and count how many were settled. - delete_transfer: only a known
pendingrecord can be deleted. The held amount is refunded to the sender and the record becomesdeleted. - Unknown commands return
False.
Why it is correct
The sender's money is taken when the offline transfer is created, so each unit of money is always in exactly one place: a balance, or a pending hold. Settlement moves it from the hold to the recipient, and deletion moves it back to the sender. A record's status changes only away from pending, so settlement and refund each happen at most once, and a deleted record can never be settled. Since validation precedes mutation, failed commands leave no partial changes.
Note that accounts start at 0 and there is no deposit, so in scripts using only these commands every transfer fails the funds check. The logic is still implemented in full.
Complexity
- Each command is O(1), except
process_offline_transfers, which is O(R) in the number of records. - Space is O(U + R) for users and records.
Reference solution
from typing import List
def run_bank_script(commands: List[str], params: List[List]) -> List:
balances = {}
records = {}
counter = 1
out = []
def valid(src, dst, amount):
if src not in balances or dst not in balances:
return False
if src == dst or amount <= 0:
return False
return balances[src] >= amount
for cmd, args in zip(commands, params):
if cmd == "create_user":
uid = args[0]
if uid in balances:
out.append(False)
else:
balances[uid] = 0
out.append(True)
elif cmd == "get_balance":
out.append(balances.get(args[0]))
elif cmd == "transfer":
src, dst, amount = args
if not valid(src, dst, amount):
out.append(False)
else:
balances[src] -= amount
balances[dst] += amount
out.append(True)
elif cmd == "offline_transfer":
src, dst, amount = args
if not valid(src, dst, amount):
out.append(False)
else:
tid = f"transfer-{counter}"
counter += 1
balances[src] -= amount
records[tid] = {
"from": src,
"to": dst,
"amount": amount,
"state": "pending",
}
out.append(tid)
elif cmd == "process_offline_transfers":
settled = 0
for rec in records.values():
if rec["state"] == "pending":
balances[rec["to"]] += rec["amount"]
rec["state"] = "completed"
settled += 1
out.append(settled)
elif cmd == "delete_transfer":
rec = records.get(args[0])
if rec is None or rec["state"] != "pending":
out.append(False)
else:
balances[rec["from"]] += rec["amount"]
rec["state"] = "deleted"
out.append(True)
else:
out.append(False)
return out