In-Memory Bank Ledger with Pending Transfers and Expiry
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate an in-memory banking system processing sequential operations, pending transfers with fixed-window expiration, and account activity tracking.
Design an in-memory ledger engine for a financial service. The system must process a list of sequential operations, maintain account balances, process delayed transfers with timed expirations, and rank accounts based on total activity.
You are given a parameter transfer_window, a list of operation names operations, and a matching list of parameter lists arguments.
Before executing any operation at a given timestamp, the engine must process all pending transfers that have expired. A transfer created at time $T_{create}$ with a window $W$ is active up to and including timestamp $T_{create} + W$. It expires as soon as an operation is processed at a timestamp $T_{current} > T_{create} + W$. When a transfer expires, its reserved funds are automatically refunded to the sender's account.
Each operation has a timestamp as its first parameter. Timestamps across all operations are guaranteed to be strictly increasing.
Supported Operations
-
create_account(timestamp, account_id)- Creates an account named
account_idwith an initial balance of0. - Returns
Trueif created successfully. - Returns
Falseifaccount_idalready exists.
- Creates an account named
-
deposit(timestamp, account_id, amount)- Adds
amounttoaccount_id's balance and increasesaccount_id's total activity count byamount. - Returns the updated balance (an integer) on success.
- Returns
Noneifaccount_iddoes not exist.
- Adds
-
pay(timestamp, account_id, amount)- Deducts
amountfromaccount_id's balance and increasesaccount_id's total activity count byamount. - Returns the updated balance (an integer) on success.
- Returns
Noneifaccount_iddoes not exist or if the available balance is less thanamount.
- Deducts
-
top_activity(timestamp, n)- Returns a list of up to
naccounts with the highest cumulative activity, formatted as[[account_id, activity], ...]. - Tie-breaking: If two accounts have the same activity score, order them lexicographically (alphabetically) by
account_id. - If
nis greater than the total number of existing accounts, return all existing accounts in ranked order.
- Returns a list of up to
-
transfer(timestamp, source_id, target_id, amount)- Immediately deducts
amountfromsource_id's balance to hold the funds. - Does not credit
target_idimmediately, and does not count towards activity scores. - Returns a transfer string ID of the form
"transfer1","transfer2", ..., incremented sequentially for every attempted transfer operation (whether successful or rejected). - Returns
None(and does not change state or increment transfer ID counter) ifsource_idortarget_iddoes not exist, ifsource_id == target_id, or ifsource_idhas insufficient funds.
- Immediately deducts
-
accept_transfer(timestamp, account_id, transfer_id)- Finalizes a pending transfer by adding the held funds to
account_id's balance. - Does not affect activity scores.
- Returns
Trueif successful. - Returns
Falseiftransfer_iddoes not exist, is not in a pending state, has already expired, or ifaccount_idis not the target account of the transfer.
- Finalizes a pending transfer by adding the held funds to
Constraints
- Timestamps are strictly increasing integers: $1 \le \text{timestamp}i < \text{timestamp}{i+1}$.
- Amounts are positive integers: $1 \le \text{amount} \le 10^9$.
- $1 \le \text{transfer_window} \le 10^5$.
- $1 \le N \le 1000$, where $N$ is the length of
operations. - Returned account rankings for
top_activitymust format each pair as a 2-element list[account_id, activity].
Examples
Example 1
Input: run_bank_operations(5, ['create_account', 'create_account', 'deposit', 'transfer', 'accept_transfer', 'top_activity'], [[1, 'alice'], [2, 'bob'], [3, 'alice', 100], [4, 'alice', 'bob', 40], [5, 'bob', 'transfer1'], [6, 2]])
Output: [True, True, 100, 'transfer1', True, [['alice', 100], ['bob', 0]]]
Example 2
Input: run_bank_operations(3, ['create_account', 'create_account', 'deposit', 'transfer', 'pay', 'top_activity'], [[1, 'a'], [2, 'b'], [3, 'a', 50], [4, 'a', 'b', 30], [5, 'a', 25], [6, 5]])
Output: [True, True, 50, 'transfer1', None, [['a', 50], ['b', 0]]]
Hints
Hint 1
Make sure to update pending transfers before executing the operation at the current timestamp.
Hint 2
Expirations occur when current_timestamp > create_timestamp + transfer_window. Refund the held money to the sender when a transfer expires.
Hint 3
Activity only increases on successful deposit and pay operations. Transfers and acceptance of transfers do not affect activity.
Hint 4
For top_activity tie-breaking, sort primarily by activity descending, and secondarily by account_id ascending (lexicographical order).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires us to track state across multiple account interactions and timed operations:
-
State Tracking:
balances: Map fromaccount_idto its current available funds.activity: Map fromaccount_idto its accumulated volume fromdepositandpay.transfers: Map from transfer ID (e.g."transfer1") to a structure recordingsource,target,amount,deadline, andstatus.
-
Expiration Handling:
- Before executing each command at timestamp $T$, check all pending transfers.
- If a transfer's deadline ($T_{create} + \text{transfer_window}$) is strictly less than $T$, mark it as
"expired"and refund the reservedamountback to thesourceaccount's balance.
-
Operation Logic:
create_account: Add tobalancesandactivitywith 0 if key does not exist.deposit: If account exists, update balance and activity, returning new balance.pay: Check existence and sufficient balance ($ balance \ge amount $). Update balance and activity, returning new balance.top_activity: Sort accounts by(-activity, account_id)and take the top $N$.transfer: Check validity (both accounts exist, source $\neq$ target, sufficient balance). Reserve funds from source, assign"transferK", and compute deadline.accept_transfer: Check validity (exists, pending, correct target). Mark as"accepted"and add funds to target.
Complexity Analysis
-
Time Complexity:
- Processing expirations: $O(K)$ per operation where $K$ is the number of transfers.
- Operations
create_account,deposit,pay,transfer,accept_transfer: $O(1)$ lookup and state updates. top_activity: $O(A \log A)$ where $A$ is the total number of accounts.- Overall time complexity for $N$ operations is bounded by $O(N \cdot (K + A \log A))$. Given $N \le 1000$, this easily runs well within time limits.
-
Space Complexity:
- $O(A + K)$ space to store accounts, activity metrics, and transfer records.
Reference Solution
from typing import List
def run_bank_operations(transfer_window: int, operations: List[str], arguments: List[List]) -> List:
balances = {}
activity = {}
transfers = {}
next_transfer_id = 1
results = []
def expire(timestamp):
for transfer in transfers.values():
if transfer["status"] == "pending" and timestamp > transfer["deadline"]:
transfer["status"] = "expired"
balances[transfer["source"]] += transfer["amount"]
for operation, args in zip(operations, arguments):
timestamp = args[0]
expire(timestamp)
if operation == "create_account":
_, account_id = args
if account_id in balances:
results.append(False)
else:
balances[account_id] = 0
activity[account_id] = 0
results.append(True)
elif operation == "deposit":
_, account_id, amount = args
if account_id not in balances:
results.append(None)
else:
balances[account_id] += amount
activity[account_id] += amount
results.append(balances[account_id])
elif operation == "pay":
_, account_id, amount = args
if account_id not in balances or balances[account_id] < amount:
results.append(None)
else:
balances[account_id] -= amount
activity[account_id] += amount
results.append(balances[account_id])
elif operation == "top_activity":
_, n = args
ranked = sorted(activity.items(), key=lambda item: (-item[1], item[0]))
results.append([[account_id, value] for account_id, value in ranked[:max(0, n)]])
elif operation == "transfer":
_, source_id, target_id, amount = args
if (source_id not in balances or target_id not in balances or
source_id == target_id or balances[source_id] < amount):
results.append(None)
else:
transfer_id = f"transfer{next_transfer_id}"
next_transfer_id += 1
balances[source_id] -= amount
transfers[transfer_id] = {
"source": source_id,
"target": target_id,
"amount": amount,
"deadline": timestamp + transfer_window,
"status": "pending",
}
results.append(transfer_id)
elif operation == "accept_transfer":
_, account_id, transfer_id = args
transfer = transfers.get(transfer_id)
if (transfer is None or transfer["status"] != "pending" or
transfer["target"] != account_id):
results.append(False)
else:
transfer["status"] = "accepted"
balances[account_id] += transfer["amount"]
results.append(True)
else:
raise ValueError(f"Unknown operation: {operation}")
return results