Stateful Banking System Ledger Engine
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate an in-memory banking ledger that processes chronologically ordered operations involving balances, leaderboards, delayed cashbacks, and account merges.
Design an in-memory banking engine that processes a stream of chronological financial queries and produces a list of string outcomes, one per query.
Each request in queries is an array of strings formatted as follows:
- Index 0: Operation name string.
- Index 1: A
timestamp(integer formatted as a string, in milliseconds, strictly increasing across queries). - Subsequent indices: Operation arguments.
Numerical outputs should not contain any currency symbols or thousands separators. Return "" (empty string) whenever an operation fails or is invalid, unless specified otherwise.
Supported Operations
1. Core Accounts
["CREATE_ACCOUNT", timestamp, account_id]- Registers a new account. Returns
"true"on success, or"false"ifaccount_idalready exists.
- Registers a new account. Returns
["DEPOSIT", timestamp, account_id, amount]- Adds
amounttoaccount_id. Returns the updated balance as a string, or""ifaccount_iddoes not exist.
- Adds
["GET_BALANCE", timestamp, account_id]- Returns the current balance of
account_idas a string, or""ifaccount_iddoes not exist.
- Returns the current balance of
2. Transfers & Leaderboards
["TRANSFER", timestamp, source_id, target_id, amount]- Transfers
amountfromsource_idtotarget_id. Returns the new balance ofsource_idas a string. - Returns
""if either account is missing, ifsource_id == target_id, or ifsource_idhas insufficient funds (no transfer occurs in these cases).
- Transfers
["TOP_SPENDERS", timestamp, n]- Returns a formatted string listing the top
nactive accounts sorted by total outgoing funds (the aggregate of all successfulTRANSFERandPAYamounts originating from that account). - Format:
"id1(total1), id2(total2)". - Tie-breaker: Sort primarily by total outgoing funds descending, then by
account_idin ascending lexicographical order. - Includes all active accounts. If fewer than
nactive accounts exist, includes all of them.
- Returns a formatted string listing the top
3. Payments & Deferred Cashbacks
["PAY", timestamp, account_id, amount]- Immediately deducts
amountfromaccount_idand generates a global payment identifier ("payment1","payment2", … incremented on each successful payment). Returns the payment ID string. - Returns
""if the account does not exist or has insufficient funds. - Each payment earns 2% cashback calculated via integer division: $\lfloor \text{amount} \times 2 / 100 \rfloor$.
- The cashback is automatically credited back to the account exactly
86400000ms (24 hours) after the paymenttimestamp.
- Immediately deducts
["GET_PAYMENT_STATUS", timestamp, account_id, payment_id]- Returns
"IN_PROGRESS"if the cashback has not yet been processed attimestamp, or"CASHBACK_RECEIVED"if it has been credited. - Returns
""ifaccount_iddoes not exist or ifpayment_idwas not created by (or inherited by) that account.
- Returns
Cashback Processing Rule: Before processing any query at time $t$, all pending cashbacks scheduled at timestamps $\le t$ must be settled and credited to their respective target accounts.
4. Account Merging
["MERGE_ACCOUNTS", timestamp, account_id_1, account_id_2]- Merges
account_id_2intoaccount_id_1. Returns"true"on success, or"false"if either account does not exist or ifaccount_id_1 == account_id_2. - Merging combines balances and cumulative spending totals into
account_id_1. Any pending cashbacks owed toaccount_id_2will be credited toaccount_id_1upon maturity. - After merging,
account_id_2is removed from active accounts. However, subsequentGET_PAYMENT_STATUSqueries for payments originally made byaccount_id_2must succeed when queried againstaccount_id_1.
- Merges
Constraints
- $1 \le \text{len(queries)} \le 10^4$
- Timestamps are strictly increasing integers in the range $[1, 10^{15}]$.
- All monetary amounts are non-negative integers in the range $[0, 10^9]$.
- All account IDs are non-empty strings.
Examples
Example 1
Input: banking_system_simulation([['CREATE_ACCOUNT', '1', 'alice'], ['CREATE_ACCOUNT', '2', 'bob'], ['DEPOSIT', '3', 'alice', '2000'], ['TRANSFER', '4', 'alice', 'bob', '500'], ['TOP_SPENDERS', '5', '2'], ['PAY', '6', 'alice', '1000'], ['GET_PAYMENT_STATUS', '7', 'alice', 'payment1'], ['GET_PAYMENT_STATUS', '86400007', 'alice', 'payment1'], ['GET_BALANCE', '86400008', 'alice']])
Output: ['true', 'true', '2000', '1500', 'alice(500), bob(0)', 'payment1', 'IN_PROGRESS', 'CASHBACK_RECEIVED', '520']
Hints
Hint 1
Use a min-heap to keep track of pending cashbacks sorted by their maturity timestamp.
Hint 2
Process all pending cashbacks from the min-heap whose maturity time is less than or equal to the current operation's timestamp before processing the operation.
Hint 3
Use a Disjoint Set Union (DSU) structure to model merged accounts. This allows pending cashbacks and old payment records to dynamically resolve to the new combined account.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating a stateful banking engine with support for basic operations, delayed async events (cashbacks), account rankings, and dynamic account consolidation (merges).
The architecture relies on three primary concepts:
-
Min-Heap for Pending Cashbacks: Events are pushed into a priority queue keyed by
(credit_timestamp, sequence_counter, payment_id, Account, amount). Prior to handling any operation at timets, we continuously pop and credit all events withcredit_timestamp <= ts. -
Disjoint Set Union (DSU) for Account Merging: When
account_id_2is merged intoaccount_id_1:- Balance and cumulative expenditure of
account_id_2are added to the root ofaccount_id_1. account_id_2is set to point toaccount_id_1as its parent (root2.parent = root1).account_id_2is deleted from the active accounts dictionary.- Any unfulfilled cashbacks or payment references tied to the node of
account_id_2automatically resolve toroot1when evaluated viafind().
- Balance and cumulative expenditure of
-
Account & Payment Mapping:
accounts: Maps activeaccount_idstrings toAccountnode objects.payments: Mapspayment_idstrings to[original_Account_node, cashback_claimed_flag].
Complexity Analysis
-
Time Complexity:
CREATE_ACCOUNT,DEPOSIT,GET_BALANCE,TRANSFER,MERGE_ACCOUNTS: $\mathcal{O}(\alpha(A))$ amortized per operation, where $\alpha$ is the inverse Ackermann function and $A$ is the number of accounts created.PAY: $\mathcal{O}(\log P)$ per insertion into the heap, where $P$ is the number of active cashbacks. Each cashback is pushed and popped exactly once, leading to $\mathcal{O}(Q \log Q)$ overall heap time.TOP_SPENDERS: Sorting all $A$ active accounts takes $\mathcal{O}(A \log A)$ per call.- Overall Time Complexity: $\mathcal{O}(Q \log Q + Q \cdot A \log A)$, which executes well within limits for $Q \le 10^4$.
-
Space Complexity:
- $\mathcal{O}(A + P)$ to store account nodes, payment history, and pending cashbacks in memory.
import heapq
from typing import List
def banking_system_simulation(queries: List[List[str]]) -> List[str]:
class Account:
def __init__(self, account_id: str):
self.account_id = account_id
self.balance = 0
self.outgoing = 0
self.parent = self
def find(acc: Account) -> Account:
if acc.parent is not acc:
acc.parent = find(acc.parent)
return acc.parent
accounts = {} # account_id -> Account object
payments = {} # payment_id -> [original_Account, is_credited_bool]
pending_cashbacks = [] # heap of (credit_time, sequence_id, payment_id, Account, cashback_amount)
payment_counter = 0
results = []
for query in queries:
op = query[0]
ts = int(query[1])
# Settle all cashbacks due on or before the current query timestamp
while pending_cashbacks and pending_cashbacks[0][0] <= ts:
_, _, p_id, acc, amount = heapq.heappop(pending_cashbacks)
root = find(acc)
root.balance += amount
payments[p_id][1] = True
if op == "CREATE_ACCOUNT":
acc_id = query[2]
if acc_id in accounts:
results.append("false")
else:
accounts[acc_id] = Account(acc_id)
results.append("true")
elif op == "DEPOSIT":
acc_id, amount = query[2], int(query[3])
if acc_id not in accounts:
results.append("")
else:
root = find(accounts[acc_id])
root.balance += amount
results.append(str(root.balance))
elif op == "GET_BALANCE":
acc_id = query[2]
if acc_id not in accounts:
results.append("")
else:
results.append(str(find(accounts[acc_id]).balance))
elif op == "TRANSFER":
src_id, tgt_id, amount = query[2], query[3], int(query[4])
if src_id not in accounts or tgt_id not in accounts or src_id == tgt_id:
results.append("")
continue
src = find(accounts[src_id])
tgt = find(accounts[tgt_id])
if src is tgt or src.balance < amount:
results.append("")
else:
src.balance -= amount
tgt.balance += amount
src.outgoing += amount
results.append(str(src.balance))
elif op == "TOP_SPENDERS":
n = int(query[2])
active_list = list(accounts.values())
active_list.sort(key=lambda a: (-find(a).outgoing, a.account_id))
top_n = active_list[:n]
formatted = ", ".join(f"{a.account_id}({find(a).outgoing})" for a in top_n)
results.append(formatted)
elif op == "PAY":
acc_id, amount = query[2], int(query[3])
if acc_id not in accounts:
results.append("")
continue
acc = find(accounts[acc_id])
if acc.balance < amount:
results.append("")
continue
acc.balance -= amount
acc.outgoing += amount
payment_counter += 1
pid = f"payment{payment_counter}"
payments[pid] = [acc, False]
cb_amount = (amount * 2) // 100
heapq.heappush(
pending_cashbacks,
(ts + 86400000, payment_counter, pid, acc, cb_amount)
)
results.append(pid)
elif op == "GET_PAYMENT_STATUS":
acc_id, pid = query[2], query[3]
if acc_id not in accounts or pid not in payments:
results.append("")
continue
curr_acc = find(accounts[acc_id])
orig_acc, status = payments[pid]
if find(orig_acc) is not curr_acc:
results.append("")
else:
results.append("CASHBACK_RECEIVED" if status else "IN_PROGRESS")
elif op == "MERGE_ACCOUNTS":
id1, id2 = query[2], query[3]
if id1 not in accounts or id2 not in accounts or id1 == id2:
results.append("false")
continue
root1 = find(accounts[id1])
root2 = find(accounts[id2])
if root1 is root2:
results.append("false")
continue
root1.balance += root2.balance
root1.outgoing += root2.outgoing
root2.parent = root1
del accounts[id2]
results.append("true")
else:
results.append("")
return results