Simulate a Time-Aware Financial Ledger
Data Structure DesignAuto-graded · 15 test casesLast updated
Process sequential financial operations with scheduled transfers, account merging, historical snapshot queries, and activity rankings using heaps and binary search.
Design an engine to process a sequence of chronological financial requests for a time-aware banking network. The function process_bank_operations(operations, arguments) accepts two list parameters: operations, containing command strings, and arguments, containing lists of positional arguments for each command.
Every command's first positional argument is an integer timestamp. Across the sequence of operations, these timestamps are non-decreasing.
Automatic Processing: Pending Scheduled Transfers
Before carrying out any command at time timestamp, all scheduled transfers due at or before timestamp (scheduled_time <= timestamp) must execute in chronological order. If multiple transfers share the exact same scheduled execution time, break ties by ordering transfer_id lexicographically ascending.
During scheduled execution:
- Re-check that both sender and recipient are active, sender $\neq$ recipient, and sender balance $\ge \text{amount}$.
- If any check fails, the transfer is dropped silently.
- On success, transfer the funds, update cumulative outbound totals, and log balance changes for both accounts at
scheduled_time(not the current operation timestamp).
Command Specifications
-
create_account(timestamp, account_id)- Creates a new account
account_id(string) with balance0. - Returns
Trueif successful, orFalseifaccount_idis currently active. - Note: If an account was previously merged away (deactivated), re-creating it succeeds and resets its state, balance, and spending history.
- Creates a new account
-
deposit(timestamp, account_id, amount)- Adds
amount(integer $> 0$) to the active accountaccount_id. - Logs the new balance at
timestamp. - Returns the updated balance as an integer, or
Noneifaccount_idis not active.
- Adds
-
transfer(timestamp, from_id, to_id, amount)- Instantly transfers
amountfromfrom_idtoto_id. - Fails if
from_idorto_idis not active,from_id == to_id, orbalances[from_id] < amount. - On success, updates balances, logs balance history for both accounts at
timestamp, addsamounttofrom_id's total outbound transfer volume, and returnsTrue. Otherwise returnsFalse.
- Instantly transfers
-
schedule_transfer(timestamp, scheduled_time, transfer_id, from_id, to_id, amount)- Registers a future transfer with unique identifier
transfer_id(string). - Returns
Falseifscheduled_time <= timestamp, iftransfer_idhas ever been used before (including previously executed or cancelled transfers), iffrom_idorto_idis not active, or iffrom_id == to_id. - Balance sufficiency is not checked at registration time.
- Returns
Trueon successful scheduling.
- Registers a future transfer with unique identifier
-
cancel_transfer(timestamp, transfer_id)- Cancels a pending scheduled transfer.
- Returns
Trueif successfully cancelled, orFalseiftransfer_idis not currently pending (e.g., non-existent, already executed, or previously cancelled).
-
merge_accounts(timestamp, target_id, source_id)- Merges active
source_idinto activetarget_id. Fails (returnsFalse) if either account is inactive ortarget_id == source_id. - Transfers
source_id's remaining balance totarget_id. (This balance movement does not count as outbound transfer volume). - Adds
source_id's cumulative outbound volume totarget_id's outbound volume. - Rebinds all currently pending transfers involving
source_idso they referencetarget_idinstead. - Deactivates
source_id(setting its active balance to 0 and logging snapshots attimestampfor both accounts). - Returns
Trueon success.
- Merges active
-
get_balance(timestamp, account_id, as_of_time)- Retrieves account balance as of
as_of_time(as_of_time <= timestamp). - Returns
Noneifaccount_idwas never created or ifas_of_timeis strictly prior to the account's initial creation time. - Returns the account's balance after processing all events up to and including
as_of_time. This query works for both active and deactivated accounts.
- Retrieves account balance as of
-
get_top_spenders(timestamp, n)- Returns a list of strings containing up to the top
nactive accounts ranked by cumulative outbound transfer volume descending. - Break ties lexicographically by
account_idascending. - Deactivated accounts are omitted. Outbound volume counts direct and scheduled transfers only (deposits and balance shifts from mergers are excluded).
- Returns a list of strings containing up to the top
Constraints
- $1 \le \text{timestamp}, \text{scheduled_time} \le 10^9$
- Total number of operations $\le 20,000$
amount$> 0$
Examples
Example 1
Input: process_bank_operations(['create_account', 'create_account', 'deposit', 'schedule_transfer', 'get_balance', 'get_balance', 'get_top_spenders'], [[1, 'A'], [1, 'B'], [2, 'A', 100], [3, 10, 't1', 'A', 'B', 40], [5, 'A', 4], [11, 'A', 10], [12, 1]])
Output: [True, True, 100, True, 100, 60, ['A']]
Hints
Hint 1
Process due scheduled transfers before every operation call by pulling from a min-heap sorted by (scheduled_time, transfer_id).
Hint 2
Use lazy deletion for heap entries: store the active scheduled parameters in a map, and remove the entry when cancelled or updated.
Hint 3
When merging accounts, rewrite the sender and receiver IDs in the pending transfer lookup dictionary while keeping the heap unchanged.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To process a sequence of time-aware financial operations, we track account states and pending transfers chronologically:
- Pending Queue & Priority Priority Heap:
- Store scheduled transfers in a min-heap containing tuples of
(scheduled_time, transfer_id). - Maintain a hash map
pendingmappingtransfer_idto(from_id, to_id, amount). - When a transfer is cancelled, delete its key from
pending. When popping from the heap, if atransfer_idis missing frompending, skip it (lazy deletion).
- Store scheduled transfers in a min-heap containing tuples of
- Account Balances and History:
- Maintain
balances,spent(total outbound volume), and a set ofactiveaccounts. - Maintain
histories[account_id]as an append-only list of(timestamp, balance)snapshots. - For
get_balance(timestamp, account_id, as_of_time), use binary search (bisect_right) over recorded timestamps to find the balance matching the snapshot at or immediately prior toas_of_time.
- Maintain
- Execution Rule:
- At the beginning of processing any operation with a given
timestamp, iterate through the heap and execute all transfers wherescheduled_time <= timestamp. - For each executed transfer, log snapshots at
scheduled_time.
- At the beginning of processing any operation with a given
Complexity Analysis
- Schedule / Cancel Transfer: $O(\log S)$ time for priority heap operations, where $S$ is the total scheduled transfers count.
- Account Merging: $O(P)$ time, where $P$ is the number of active pending transfers, to update account references.
- Get Balance: $O(\log H)$ time via binary search, where $H$ is the history snapshot count for the account.
- Get Top Spenders: $O(A \log A)$ time, where $A$ is the count of currently active accounts.
- Space Complexity: $O(N + S)$ auxiliary space across all events and data structures.
import heapq
from bisect import bisect_right
from typing import List
def process_bank_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
balances = {}
histories = {}
active = set()
spent = {}
pending = {}
used_transfer_ids = set()
schedule_heap = []
results = []
def record(account_id: str, time: int) -> None:
histories[account_id].append((time, balances[account_id]))
def execute_due(time: int) -> None:
while schedule_heap and schedule_heap[0][0] <= time:
scheduled_time, transfer_id = heapq.heappop(schedule_heap)
transfer = pending.pop(transfer_id, None)
if transfer is None:
continue
from_id, to_id, amount = transfer
if (from_id in active and to_id in active and from_id != to_id
and balances[from_id] >= amount):
balances[from_id] -= amount
balances[to_id] += amount
spent[from_id] += amount
record(from_id, scheduled_time)
record(to_id, scheduled_time)
for operation, args in zip(operations, arguments):
timestamp = args[0]
execute_due(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
spent[account_id] = 0
histories[account_id] = [(timestamp, 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
record(account_id, timestamp)
results.append(balances[account_id])
elif operation == "transfer":
_, from_id, to_id, amount = args
if (from_id not in active or to_id not in active or from_id == to_id
or balances[from_id] < amount):
results.append(False)
else:
balances[from_id] -= amount
balances[to_id] += amount
spent[from_id] += amount
record(from_id, timestamp)
record(to_id, timestamp)
results.append(True)
elif operation == "schedule_transfer":
_, scheduled_time, transfer_id, from_id, to_id, amount = args
if (scheduled_time <= timestamp or transfer_id in used_transfer_ids
or from_id not in active or to_id not in active or from_id == to_id):
results.append(False)
else:
used_transfer_ids.add(transfer_id)
pending[transfer_id] = (from_id, to_id, amount)
heapq.heappush(schedule_heap, (scheduled_time, transfer_id))
results.append(True)
elif operation == "cancel_transfer":
_, transfer_id = args
if transfer_id in pending:
del pending[transfer_id]
results.append(True)
else:
results.append(False)
elif operation == "merge_accounts":
_, target_id, source_id = args
if target_id not in active or source_id not in active or target_id == source_id:
results.append(False)
else:
balances[target_id] += balances[source_id]
balances[source_id] = 0
spent[target_id] += spent[source_id]
spent[source_id] = 0
active.remove(source_id)
record(target_id, timestamp)
record(source_id, timestamp)
for tid, (fid, tid_acc, amt) in list(pending.items()):
pending[tid] = (
target_id if fid == source_id else fid,
target_id if tid_acc == source_id else tid_acc,
amt,
)
results.append(True)
elif operation == "get_balance":
_, account_id, as_of_time = args
events = histories.get(account_id)
if events is None:
results.append(None)
else:
times = [e[0] for e in events]
idx = bisect_right(times, as_of_time) - 1
results.append(events[idx][1] if idx >= 0 else None)
elif operation == "get_top_spenders":
_, n = args
ranked = sorted(active, key=lambda acc: (-spent[acc], acc))
results.append(ranked[:n])
else:
raise ValueError(f"Unknown operation: {operation}")
return results