Multi-Stage In-Memory Ledger with Scheduled Settlements and Merges
Hard · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Implement a stateful BankingSystem class in memory across four cumulative stages. Every stage builds directly on the earlier ones without breaking existing behavior.
Every public method takes an integer timestamp as its first argument:
- Calls must arrive in non-decreasing timestamp order. If a call supplies a timestamp strictly less than the previous call's timestamp, raise ValueError immediately before modifying any state.
- Due-payment settlement gate: Before performing its own operation, every public method must settle all pending scheduled payments whose due_time <= timestamp, ordered first by due_time ascending and then by scheduling order ("payment1", "payment2", ...).
- All amounts are integers. Any invalid request returns False or None (as specified below) and leaves balances, histories, rankings, and scheduled payments completely unchanged.
Stage 1 — Accounts, Deposits, Transfers, and Ledgers
create_account(timestamp: int, account_id: str) -> bool: Createsaccount_idwith balance0, outgoing total0, and an empty ledger, returningTrue. ReturnsFalseifaccount_idalready exists.deposit(timestamp: int, account_id: str, amount: int) -> Optional[int]: Addsamounttoaccount_id, appends(timestamp, "deposit", amount)to its ledger, and returns the updated balance. ReturnsNoneifaccount_iddoes not exist oramount <= 0.transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: Movesamountfromsource_idtotarget_id, increasessource_id's outgoing total byamount, appends(timestamp, "transfer_out", -amount)tosource_id's ledger and(timestamp, "transfer_in", amount)totarget_id's ledger, and returnssource_id's new balance. ReturnsNoneif either account is missing,source_id == target_id,amount <= 0, orsource_id's balance is less thanamount.get_balance(timestamp: int, account_id: str) -> Optional[int]: Returns the current balance ofaccount_id, orNoneifaccount_iddoes not exist.get_history(timestamp: int, account_id: str) -> Optional[List[Tuple[int, str, int]]]: Returnsaccount_id's completed balance changes as[(entry_timestamp, kind, signed_amount), ...]from oldest to newest, orNoneifaccount_iddoes not exist.
Stage 2 — Outgoing Spend Leaderboard
top_spenders(timestamp: int, n: int) -> List[Tuple[str, int]]: Ranks all active accounts by cumulative outgoing total in descending order, breaking ties alphabetically (AtoZ) byaccount_id, and returns up tonpairs(account_id, outgoing_total).- Outgoing total equals the sum of completed
transferamounts sent plus"EXECUTED"scheduled payment amounts sent (deposits, incoming funds, and unexecuted payments never count). - Accounts with
0outgoing total are included. Ifnexceeds the number of active accounts, return all active accounts; ifn <= 0, return[].
- Outgoing total equals the sum of completed
Stage 3 — Delayed Recipient-Accepted Payments
schedule_payment(timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: Registers a payment ofamountfromsource_idtotarget_iddue atdue_time = timestamp + delaywith initial status"SCHEDULED". Valid calls return sequential IDs"payment1","payment2", ... (rejected calls do not advance the counter). ReturnsNoneif either account is missing,source_id == target_id,amount <= 0, ordelay <= 0. Funds are verified only atdue_time.accept_payment(timestamp: int, account_id: str, payment_id: str) -> bool: Ifpayment_idexists, its status is still"SCHEDULED"(meaningtimestamp < due_time), andaccount_idequals the designated recipienttarget_id, updates status to"ACCEPTED"and returnsTrue; otherwise returnsFalse.- Settlement at
due_time:"SCHEDULED"(never accepted beforedue_time) transitions to"EXPIRED"without moving funds."ACCEPTED"checks the payer's balance atdue_time: if< amount, status transitions permanently to"FAILED"with no retry; otherwiseamountmoves from payer to recipient, payer's outgoing total increases byamount, ledger entries(due_time, "payment_out", -amount)and(due_time, "payment_in", amount)are recorded usingdue_time, and status becomes"EXECUTED"."CANCELLED"remains"CANCELLED"with no effect.
get_payment_status(timestamp: int, payment_id: str) -> Optional[str]: Returns"SCHEDULED","ACCEPTED","EXECUTED","EXPIRED","FAILED", or"CANCELLED", orNoneifpayment_idis unknown.
Stage 4 — Account Consolidation
merge_accounts(timestamp: int, keep_id: str, other_id: str) -> bool: Absorbsother_idintokeep_idand returnsTrue, or returnsFalseifkeep_id == other_idor either account does not exist.keep_id's balance and outgoing total each increase byother_id's values, and both ledgers are combined in chronological order.other_idceases to exist (create_accountmay later reuseother_idas a fresh empty account).- Any pending (
"SCHEDULED"or"ACCEPTED") payment referencingother_idas payer or recipient is re-pointed tokeep_id. If re-pointing makes payer equal to recipient (keep_id == keep_id), its status becomes"CANCELLED".
Examples
Example 1
Input:
bank = BankingSystem()
bank.create_account(1, "mia") # True
bank.create_account(1, "leo") # True
bank.create_account(1, "zoe") # True
bank.deposit(2, "mia", 250) # 250
bank.deposit(3, "leo", 180) # 180
bank.transfer(4, "mia", "zoe", 90) # 160
bank.transfer(5, "leo", "zoe", 90) # 90
bank.transfer(6, "leo", "mia", 500) # None (insufficient funds)
bank.top_spenders(7, 2)
bank.get_history(7, "zoe")
Output:
bank.top_spenders(7, 2) # [("leo", 90), ("mia", 90)]
bank.get_history(7, "zoe") # [(4, "transfer_in", 90), (5, "transfer_in", 90)]
Walk-through: "mia" and "leo" each send 90 to "zoe", tying at 90 outgoing spend, so top_spenders orders "leo" ahead of "mia" alphabetically. The rejected 500 overdraft at t = 6 leaves balances, spend totals, and ledgers untouched.
Example 2
Input:
bank = BankingSystem()
for acct in ("kai", "ava", "noa"):
bank.create_account(1, acct)
bank.deposit(2, "kai", 120) # 120
p1 = bank.schedule_payment(3, "kai", "ava", 75, 7) # "payment1" (due at 10)
p2 = bank.schedule_payment(4, "kai", "noa", 60, 6) # "payment2" (due at 10)
p3 = bank.schedule_payment(5, "kai", "ava", 20, 3) # "payment3" (due at 8)
bank.accept_payment(6, "noa", p2) # True (accepted 1st)
bank.accept_payment(7, "ava", p1) # True (accepted 2nd)
bank.accept_payment(8, "ava", p3) # False (already expired at t=8)
bank.get_balance(11, "kai")
Output:
bank.accept_payment(8, "ava", p3) # False
bank.get_balance(11, "kai") # 45
bank.get_payment_status(11, p1) # "EXECUTED"
bank.get_payment_status(11, p2) # "FAILED"
bank.get_payment_status(11, p3) # "EXPIRED"
Walk-through: When accept_payment(8, "ava", "payment3") runs, the settlement gate processes due_time = 8 first and marks unaccepted "payment3" as "EXPIRED", so acceptance returns False. At t = 10, "payment1" and "payment2" share due_time = 10; scheduling order runs "payment1" first (120 - 75 = 45), leaving "kai" short of 60 so "payment2" becomes "FAILED".
Example 3
Input:
bank = BankingSystem()
for acct in ("hq", "branch", "vendor"):
bank.create_account(1, acct)
bank.deposit(2, "hq", 60)
bank.deposit(3, "branch", 150)
bank.transfer(4, "branch", "vendor", 40) # 110
p1 = bank.schedule_payment(5, "branch", "vendor", 50, 10) # "payment1" (due at 15)
p2 = bank.schedule_payment(5, "hq", "branch", 25, 10) # "payment2" (due at 15)
bank.accept_payment(6, "vendor", p1) # True
bank.accept_payment(6, "branch", p2) # True
bank.merge_accounts(8, "hq", "branch") # True
bank.get_balance(15, "hq")
bank.top_spenders(15, 2)
Output:
bank.get_payment_status(8, p2) # "CANCELLED"
bank.get_balance(15, "hq") # 120
bank.top_spenders(15, 2) # [("hq", 90), ("vendor", 0)]
Walk-through: Merging "branch" into "hq" at t = 8 combines their balances (60 + 110 = 170) and outgoing totals (0 + 40 = 40), cancels "payment2" because both endpoints are now "hq", and re-points "payment1" from "branch" to "hq". At t = 15, "payment1" executes (170 - 50 = 120), bringing "hq"'s outgoing total to 40 + 50 = 90.
Constraints
timestampis an integer arriving in non-decreasing order across calls (timestamp < previous_timestampraisesValueError).account_idis a string;amount,delay, andnare integers.- Valid
deposit,transfer, andschedule_paymentcalls requireamount > 0(anddelay > 0forschedule_payment). - Up to
10^4total operations across accounts, transfers, scheduled payments, leaderboard queries, and merges.
Step-by-step walkthrough
Pin down the rules and method contracts
In a multi-stage ledger design problem, early choices determine whether later stages require a painful rewrite. Before writing code, lock down every invariant:
- Time moves forward: every method receives
timestampfirst. Iftimestampis smaller than the previous call's timestamp, raiseValueErrorimmediately. - All-or-nothing validation: an invalid call returns
FalseorNoneand leaves zero trace—no partial balance change and no history entry. - Self-transfers are invalid: transferring from an account to itself would leave the balance unchanged while artificially inflating
top_spenders. - Outgoing value: only successful transfers sent and executed scheduled payments sent count toward
top_spenders. Deposits, incoming money, and failed/expired/cancelled payments do not count. - Due-time priority: a scheduled payment with
due_time <= timestampruns before the operation attimestamp. If two payments share the samedue_time, they run in scheduling order (payment1,payment2, ...), regardless of the order in which they were accepted.
Method Success return Failure return & causes create_account(ts, id)TrueFalseifidalready existsdeposit(ts, id, amount)new balance Noneif missing account oramount <= 0transfer(ts, src, dst, amount)src's new balanceNoneif missing account,src == dst,amount <= 0, or insufficient fundsget_balance(ts, id)/get_history(ts, id)balance / [(ts, kind, signed_amount), ...]Noneif missing accounttop_spenders(ts, n)[(id, outgoing_total), ...][]ifn <= 0schedule_payment(ts, src, dst, amount, delay)"payment1","payment2", ...Noneif missing account,src == dst,amount <= 0, ordelay <= 0accept_payment(ts, id, payment_id)TrueFalseif unknown,idis not recipient, or status is notSCHEDULEDget_payment_status(ts, payment_id)status string Noneif unknownmerge_accounts(ts, keep_id, other_id)TrueFalseifkeep_id == other_idor either account is missing- Time moves forward: every method receives
Design the Account and Payment records
Ask what each account needs to remember across all four levels:
balance: current integer funds.outgoing: a running total of money sent out. Updating one integer whenever money moves takes O(1) time and avoids rescanning full transaction histories duringtop_spenders.history: a list of(timestamp, kind, signed_amount)tuples in chronological order. Storing signed amounts (+100for deposits,-70for outgoing transfers) makes past-balance queries a simple sum of prefixes, and Level 4 can merge two histories by timestamp.
A scheduled payment is stored as its own
Paymentobject so Level 3 can look up its status by ID and Level 4 can rewrite itssourceortargetwhen accounts merge:recipient accepts (before due_time) SCHEDULED ------------------------> ACCEPTED | | due_time | due_time | (unaccepted) +----------------+----------------+ v | payer has >= amount | payer has < amount EXPIRED v v EXECUTED FAILED (money moves at due_time) (no retry) (If a merge turns SCHEDULED or ACCEPTED into source == target -> CANCELLED)from typing import Dict, List, Optional, Tuple import functools import heapq # Lifecycle states of a scheduled payment. SCHEDULED = "SCHEDULED" # created; waiting for the recipient to accept before due_time ACCEPTED = "ACCEPTED" # accepted by recipient; executes at due_time if funds suffice EXECUTED = "EXECUTED" # money moved at due_time and counted toward outgoing total EXPIRED = "EXPIRED" # reached due_time without being accepted by the recipient FAILED = "FAILED" # accepted, but payer lacked sufficient funds at due_time CANCELLED = "CANCELLED" # account merge turned it into a self-payment (source == target) class Account: def __init__(self, account_id: str) -> None: self.account_id = account_id self.balance = 0 # Running sum of money sent via transfers and executed payments (used by top_spenders). self.outgoing = 0 # Chronological ledger of [(timestamp, kind, signed_amount)], e.g. [(2, "deposit", 100)]. self.history: List[Tuple[int, str, int]] = [] class Payment: def __init__(self, payment_id: str, source: str, target: str, amount: int, due_time: int) -> None: self.payment_id = payment_id self.source = source self.target = target self.amount = amount self.due_time = due_time self.status = SCHEDULEDSettle due payments before every operation
Suppose a payment is due at
t = 10, and no caller talks to the bank betweent = 6andt = 12. Whenget_balance(12, "A")ortop_spenders(12, 3)arrives, the bank must first catch up tot = 12by settling the payment att = 10.To find due payments quickly and in deterministic order, store pending payments in a min-heap
_dueof(due_time, sequence_num, payment_id):Heap entries: (due_time, sequence_num, payment_id) [(8, 1, "payment1"), (10, 2, "payment2"), (10, 3, "payment3")] ^ smallest due_time is always at index 0; equal due_times (10 == 10) are ordered by sequence_num (2 before 3)Rather than pasting
self._process_due(timestamp)into ten methods (and risking forgetting one), wrap every public method with a@processes_due_paymentsdecorator:def processes_due_payments(method): """Decorator for every public method: advance simulation clock to `timestamp` and settle all due payments before running the requested operation.""" @functools.wraps(method) def wrapper(self, timestamp, *args, **kwargs): # Forward *args and **kwargs so callers may pass positional or keyword arguments. self._process_due(timestamp) return method(self, timestamp, *args, **kwargs) return wrapperInside
_process_due, check timestamp ordering first, then pop and settle whiledue_time <= timestamp:class BankingSystem: def __init__(self) -> None: self._accounts: Dict[str, Account] = {} self._payments: Dict[str, Payment] = {} self._due: List[Tuple[int, int, str]] = [] self._payment_count = 0 self._last_timestamp: Optional[int] = None def _process_due(self, timestamp: int) -> None: # Phase 1: enforce non-decreasing timestamps before mutating any state. if self._last_timestamp is not None and timestamp < self._last_timestamp: raise ValueError("operations must arrive in non-decreasing timestamp order") self._last_timestamp = timestamp # Phase 2: settle every scheduled payment whose due_time is <= current timestamp. # Using <= ensures a payment due at t runs strictly before an operation called at t. while self._due and self._due[0][0] <= timestamp: _, _, payment_id = heapq.heappop(self._due) payment = self._payments[payment_id] self._settle(payment)Implement Level 1: accounts, deposits, and transfers
Every mutating method validates all preconditions before touching any balance or history. Both
transferand executed scheduled payments move money between two accounts in the exact same way, so extract a_movehelper that updatessource.balance,source.outgoing,target.balance, and bothhistorylists together. Inget_history, returnlist(account.history)so an external caller mutating the returned list cannot corrupt the bank's ledger:def _move(self, timestamp: int, source: Account, target: Account, amount: int, kind: str) -> None: # Update balances, outgoing counter, and both histories together in one place. source.balance -= amount source.outgoing += amount source.history.append((timestamp, kind + "_out", -amount)) target.balance += amount target.history.append((timestamp, kind + "_in", amount)) @processes_due_payments def create_account(self, timestamp: int, account_id: str) -> bool: if account_id in self._accounts: return False self._accounts[account_id] = Account(account_id) return True @processes_due_payments def deposit(self, timestamp: int, account_id: str, amount: int) -> Optional[int]: account = self._accounts.get(account_id) if account is None or amount <= 0: return None account.balance += amount account.history.append((timestamp, "deposit", amount)) return account.balance @processes_due_payments def transfer(self, timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: source = self._accounts.get(source_id) target = self._accounts.get(target_id) # Validate both accounts, disallow self-transfers, and check balance before mutating. if source is None or target is None or source_id == target_id or amount <= 0: return None if source.balance < amount: return None self._move(timestamp, source, target, amount, "transfer") return source.balance @processes_due_payments def get_balance(self, timestamp: int, account_id: str) -> Optional[int]: account = self._accounts.get(account_id) if account is None: return None return account.balance @processes_due_payments def get_history(self, timestamp: int, account_id: str) -> Optional[List[Tuple[int, str, int]]]: account = self._accounts.get(account_id) if account is None: return None # Return a shallow copy so callers cannot mutate the account's internal ledger. return list(account.history)Implement Level 2: rank top spenders
Because
_movekeepsaccount.outgoingup to date on every outgoing transfer and executed payment,top_spendersonly needs to sort the existing accounts and take the firstn.Negating
account.outgoingin the sort key(-account.outgoing, account.account_id)places higher spenders first while breaking ties alphabetically ("a"before"b"). Checkn <= 0explicitly up front—in Python,ranked[:-1]would return every element except the last instead of[]!@processes_due_payments def top_spenders(self, timestamp: int, n: int) -> List[Tuple[str, int]]: # Guard n <= 0 explicitly because Python slicing ranked[:negative] drops from the end. if n <= 0: return [] ranked = sorted(self._accounts.values(), key=_spender_rank) result: List[Tuple[str, int]] = [] for account in ranked[:n]: result.append((account.account_id, account.outgoing)) return resultdef _spender_rank(account: Account) -> Tuple[int, str]: """Sort key: larger outgoing total first (-outgoing), ties broken by account_id A to Z.""" return (-account.outgoing, account.account_id)Implement Level 3: schedule, accept, and settle payments
When scheduling a payment, do not check the payer's balance yet—the payer might receive a deposit before
due_time, or spend their money beforedue_time. Rejectdelay <= 0because a scheduled payment must lie strictly in the future so the recipient has a chance to accept it.Notice two subtle details in
_settleandaccept_payment:- Because
@processes_due_paymentsruns beforeaccept_payment, callingaccept_paymentattimestamp == due_timefinds the payment already popped and markedEXPIRED, sopayment.status != SCHEDULEDcleanly returnsFalse. - When an
ACCEPTEDpayment executes,_moveis called withpayment.due_time—not the timestamp of whichever later operation woke up_process_due. That keeps history timestamps faithful to when money actually moved.
def _settle(self, payment: Payment) -> None: if payment.status == SCHEDULED: # Recipient did not accept strictly before due_time, so the payment expires. payment.status = EXPIRED elif payment.status == ACCEPTED: source = self._accounts[payment.source] if source.balance < payment.amount: # Insufficient funds at due_time fails permanently with no retry. payment.status = FAILED else: target = self._accounts[payment.target] # Stamp history with payment.due_time (when money actually moved), # not the later caller timestamp that triggered _process_due. self._move(payment.due_time, source, target, payment.amount, "payment") payment.status = EXECUTED # If status is CANCELLED (from an earlier merge), leave it CANCELLED and do nothing. @processes_due_payments def schedule_payment(self, timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: if source_id not in self._accounts or target_id not in self._accounts: return None # delay <= 0 is invalid because a payment must be scheduled strictly in the future. if source_id == target_id or amount <= 0 or delay <= 0: return None self._payment_count += 1 payment_id = "payment" + str(self._payment_count) due_time = timestamp + delay self._payments[payment_id] = Payment(payment_id, source_id, target_id, amount, due_time) heapq.heappush(self._due, (due_time, self._payment_count, payment_id)) return payment_id @processes_due_payments def accept_payment(self, timestamp: int, account_id: str, payment_id: str) -> bool: payment = self._payments.get(payment_id) # Only the target recipient can accept, and only while status is still SCHEDULED. # If timestamp >= due_time, _process_due already marked it EXPIRED before we got here. if payment is None or payment.status != SCHEDULED or payment.target != account_id: return False payment.status = ACCEPTED return True @processes_due_payments def get_payment_status(self, timestamp: int, payment_id: str) -> Optional[str]: payment = self._payments.get(payment_id) if payment is None: return None return payment.status- Because
Implement Level 4: merge accounts and trace a full timeline
When
merge_accounts(ts, keep_id, other_id)runs, trace every placeother_idcan live:_accounts[other_id]: pop it soother_iddisappears (and can later be recreated from scratch).balance,outgoing, andhistory: addother's totals intokeepand merge both history lists sorted by timestamp.- Pending payments inside
self._due: rewritepayment.sourceandpayment.targetfromother_idtokeep_id. If a pending payment was betweenkeep_idandother_id, both endpoints are nowkeep_id; mark itCANCELLEDand leave it in the heap to be harmlessly discarded when popped.
@processes_due_payments def merge_accounts(self, timestamp: int, keep_id: str, other_id: str) -> bool: # Phase 1: reject self-merge or missing accounts without changing anything. if keep_id == other_id or keep_id not in self._accounts or other_id not in self._accounts: return False # Phase 2: fold balances, outgoing totals, and time-ordered histories into keep_id. keep = self._accounts[keep_id] other = self._accounts.pop(other_id) keep.balance += other.balance keep.outgoing += other.outgoing keep.history = sorted(keep.history + other.history, key=_entry_time) # Phase 3: re-point every pending payment in the heap that still names other_id. # Updating them now ensures that if other_id is created again later, the new account # will not inherit old pending payments. for _, _, payment_id in self._due: payment = self._payments[payment_id] if payment.status != SCHEDULED and payment.status != ACCEPTED: continue if payment.source == other_id: payment.source = keep_id if payment.target == other_id: payment.target = keep_id if payment.source == payment.target: # A payment between keep_id and other_id is now a self-payment: cancel it. payment.status = CANCELLED return Truedef _entry_time(entry: Tuple[int, str, int]) -> int: """Sort key for history tuples (timestamp, kind, signed_amount).""" return entry[0]Trace a complete timeline with accounts
"kai","ava", and"noa"created att = 1(extending Example 2 with a stage-4 merge):t call return state after call -- -------------------------------------------- ------------------------------ ---------------------------------- 2 deposit("kai", 120) 120 kai=120, ava=0, noa=0 3 schedule_payment("kai"->"ava", 75, delay=7) "payment1" due=10, seq=1, SCHEDULED 4 schedule_payment("kai"->"noa", 60, delay=6) "payment2" due=10, seq=2, SCHEDULED 5 schedule_payment("kai"->"ava", 20, delay=3) "payment3" due=8, seq=3, SCHEDULED 6 accept_payment("noa", "payment2") True payment2 ACCEPTED (accepted 1st) 7 accept_payment("ava", "payment1") True payment1 ACCEPTED (accepted 2nd) 8 accept_payment("ava", "payment3") -> _process_due(8): pop "payment3" -> EXPIRED False payment3 EXPIRED 11 get_balance("kai") -> _process_due(11): pop (10, 1, "payment1"): kai has 120 >= 75 -> EXECUTED at t=10 kai=45, ava=75, kai.outgoing=75 pop (10, 2, "payment2"): kai has 45 < 60 -> FAILED 45 11 top_spenders(3) [("kai",75),("ava",0),("noa",0)] 12 merge_accounts("kai", "ava") True kai=45+75=120, kai.outgoing=75Complete solution
from typing import Dict, List, Optional, Tuple import functools import heapq # Lifecycle states of a scheduled payment. SCHEDULED = "SCHEDULED" # created; waiting for the recipient to accept before due_time ACCEPTED = "ACCEPTED" # accepted by recipient; executes at due_time if funds suffice EXECUTED = "EXECUTED" # money moved at due_time and counted toward outgoing total EXPIRED = "EXPIRED" # reached due_time without being accepted by the recipient FAILED = "FAILED" # accepted, but payer lacked sufficient funds at due_time CANCELLED = "CANCELLED" # account merge turned it into a self-payment (source == target) class Account: def __init__(self, account_id: str) -> None: self.account_id = account_id self.balance = 0 # Running sum of money sent via transfers and executed payments (used by top_spenders). self.outgoing = 0 # Chronological ledger of [(timestamp, kind, signed_amount)], e.g. [(2, "deposit", 100)]. self.history: List[Tuple[int, str, int]] = [] class Payment: def __init__(self, payment_id: str, source: str, target: str, amount: int, due_time: int) -> None: self.payment_id = payment_id self.source = source self.target = target self.amount = amount self.due_time = due_time self.status = SCHEDULED def processes_due_payments(method): """Decorator for every public method: advance simulation clock to `timestamp` and settle all due payments before running the requested operation.""" @functools.wraps(method) def wrapper(self, timestamp, *args, **kwargs): # Forward *args and **kwargs so callers may pass positional or keyword arguments. self._process_due(timestamp) return method(self, timestamp, *args, **kwargs) return wrapper class BankingSystem: def __init__(self) -> None: # _accounts: maps account_id -> Account, e.g. {"a": Account("a")}. self._accounts: Dict[str, Account] = {} # _payments: maps payment_id -> Payment for all payments ever scheduled. self._payments: Dict[str, Payment] = {} # _due: min-heap of (due_time, sequence_num, payment_id), e.g. [(10, 1, "payment1")]. # sequence_num breaks ties when two payments share the exact same due_time. self._due: List[Tuple[int, int, str]] = [] self._payment_count = 0 self._last_timestamp: Optional[int] = None # ---- shared helpers -------------------------------------------------------------- def _process_due(self, timestamp: int) -> None: # Phase 1: enforce non-decreasing timestamps before mutating any state. if self._last_timestamp is not None and timestamp < self._last_timestamp: raise ValueError("operations must arrive in non-decreasing timestamp order") self._last_timestamp = timestamp # Phase 2: settle every scheduled payment whose due_time is <= current timestamp. # Using <= ensures a payment due at t runs strictly before an operation called at t. while self._due and self._due[0][0] <= timestamp: _, _, payment_id = heapq.heappop(self._due) payment = self._payments[payment_id] self._settle(payment) def _settle(self, payment: Payment) -> None: if payment.status == SCHEDULED: # Recipient did not accept strictly before due_time, so the payment expires. payment.status = EXPIRED elif payment.status == ACCEPTED: source = self._accounts[payment.source] if source.balance < payment.amount: # Insufficient funds at due_time fails permanently with no retry. payment.status = FAILED else: target = self._accounts[payment.target] # Stamp history with payment.due_time (when money actually moved), # not the later caller timestamp that triggered _process_due. self._move(payment.due_time, source, target, payment.amount, "payment") payment.status = EXECUTED # If status is CANCELLED (from an earlier merge), leave it CANCELLED and do nothing. def _move(self, timestamp: int, source: Account, target: Account, amount: int, kind: str) -> None: # Update balances, outgoing counter, and both histories together in one place. source.balance -= amount source.outgoing += amount source.history.append((timestamp, kind + "_out", -amount)) target.balance += amount target.history.append((timestamp, kind + "_in", amount)) # ---- Level 1 ----------------------------------------------------------------------- @processes_due_payments def create_account(self, timestamp: int, account_id: str) -> bool: if account_id in self._accounts: return False self._accounts[account_id] = Account(account_id) return True @processes_due_payments def deposit(self, timestamp: int, account_id: str, amount: int) -> Optional[int]: account = self._accounts.get(account_id) if account is None or amount <= 0: return None account.balance += amount account.history.append((timestamp, "deposit", amount)) return account.balance @processes_due_payments def transfer(self, timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: source = self._accounts.get(source_id) target = self._accounts.get(target_id) # Validate both accounts, disallow self-transfers, and check balance before mutating. if source is None or target is None or source_id == target_id or amount <= 0: return None if source.balance < amount: return None self._move(timestamp, source, target, amount, "transfer") return source.balance @processes_due_payments def get_balance(self, timestamp: int, account_id: str) -> Optional[int]: account = self._accounts.get(account_id) if account is None: return None return account.balance @processes_due_payments def get_history(self, timestamp: int, account_id: str) -> Optional[List[Tuple[int, str, int]]]: account = self._accounts.get(account_id) if account is None: return None # Return a shallow copy so callers cannot mutate the account's internal ledger. return list(account.history) # ---- Level 2 ----------------------------------------------------------------------- @processes_due_payments def top_spenders(self, timestamp: int, n: int) -> List[Tuple[str, int]]: # Guard n <= 0 explicitly because Python slicing ranked[:negative] drops from the end. if n <= 0: return [] ranked = sorted(self._accounts.values(), key=_spender_rank) result: List[Tuple[str, int]] = [] for account in ranked[:n]: result.append((account.account_id, account.outgoing)) return result # ---- Level 3 ----------------------------------------------------------------------- @processes_due_payments def schedule_payment(self, timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: if source_id not in self._accounts or target_id not in self._accounts: return None # delay <= 0 is invalid because a payment must be scheduled strictly in the future. if source_id == target_id or amount <= 0 or delay <= 0: return None self._payment_count += 1 payment_id = "payment" + str(self._payment_count) due_time = timestamp + delay self._payments[payment_id] = Payment(payment_id, source_id, target_id, amount, due_time) heapq.heappush(self._due, (due_time, self._payment_count, payment_id)) return payment_id @processes_due_payments def accept_payment(self, timestamp: int, account_id: str, payment_id: str) -> bool: payment = self._payments.get(payment_id) # Only the target recipient can accept, and only while status is still SCHEDULED. # If timestamp >= due_time, _process_due already marked it EXPIRED before we got here. if payment is None or payment.status != SCHEDULED or payment.target != account_id: return False payment.status = ACCEPTED return True @processes_due_payments def get_payment_status(self, timestamp: int, payment_id: str) -> Optional[str]: payment = self._payments.get(payment_id) if payment is None: return None return payment.status # ---- Level 4 ----------------------------------------------------------------------- @processes_due_payments def merge_accounts(self, timestamp: int, keep_id: str, other_id: str) -> bool: # Phase 1: reject self-merge or missing accounts without changing anything. if keep_id == other_id or keep_id not in self._accounts or other_id not in self._accounts: return False # Phase 2: fold balances, outgoing totals, and time-ordered histories into keep_id. keep = self._accounts[keep_id] other = self._accounts.pop(other_id) keep.balance += other.balance keep.outgoing += other.outgoing keep.history = sorted(keep.history + other.history, key=_entry_time) # Phase 3: re-point every pending payment in the heap that still names other_id. # Updating them now ensures that if other_id is created again later, the new account # will not inherit old pending payments. for _, _, payment_id in self._due: payment = self._payments[payment_id] if payment.status != SCHEDULED and payment.status != ACCEPTED: continue if payment.source == other_id: payment.source = keep_id if payment.target == other_id: payment.target = keep_id if payment.source == payment.target: # A payment between keep_id and other_id is now a self-payment: cancel it. payment.status = CANCELLED return True def _spender_rank(account: Account) -> Tuple[int, str]: """Sort key: larger outgoing total first (-outgoing), ties broken by account_id A to Z.""" return (-account.outgoing, account.account_id) def _entry_time(entry: Tuple[int, str, int]) -> int: """Sort key for history tuples (timestamp, kind, signed_amount).""" return entry[0]✅ Submit now — all tests should pass.
Intuition & how it works
Picture a bank teller who keeps a sorted tray of post-dated checks beside the window. Because there is no background timer running between customer visits, the teller follows one ironclad rule whenever a customer walks up at time T: before answering any question or moving any money, pull every post-dated check whose due date is at or before T from the front of the tray and settle it in exact order. Only after the tray is caught up to T does the teller handle the customer's actual request.
A naive implementation quickly tangles itself across the four levels. If you recompute top_spenders by scanning every account's full history on each query, rankings slow down as histories grow; if you check for due payments only inside transfer and get_balance, calls like top_spenders or merge_accounts read stale balances; and if merge_accounts combines two balances without updating pending post-dated checks, a check scheduled earlier will crash when the merged-away account ID is gone—or worse, charge a brand-new customer who later reuses that ID.
Instead, we store each account's running outgoing total alongside its balance and chronological history, keep pending payments in a min-heap (a priority queue that always keeps the smallest element at the top for fast O(log P) insertion and removal), and wrap every public method with a decorator (a wrapper function that automatically runs shared setup code before the method body) that drains all due payments first. Walk through four events to see how everything stays in sync:
t = 2:deposit("kai", 120)setskai.balance = 120.t = 3:schedule_payment("kai", "ava", 75, delay=7)pushes(due=10, seq=1, "payment1")onto the min-heap with statusSCHEDULED.t = 7:accept_payment("ava", "payment1")flips status toACCEPTED(no money moves yet).t = 11:top_spenders(11, 2)arrives. Before sorting accounts, the decorator pops"payment1"(since10 <= 11), seeskai.balance >= 75, moves75from"kai"to"ava"stamped at time10, and adds75tokai.outgoing—sotop_spendersimmediately returns[("kai", 75), ("ava", 0)].
Complexity
Let A be the number of active accounts, P be the number of pending payments currently in the heap, and H be the number of history entries on an account.
create_account,deposit,transfer,get_balance,accept_payment,get_payment_status: O(1) time for their own work (plus the due-payment gate), because each performs a constant number of dictionary lookups, balance updates, and list appends.- Due-payment gate (
_process_due): O(k log P) time whenkpayments come due at once, because popping each due item from the min-heap of sizePtakes O(log P) time. Across the entire run, each scheduled payment is pushed once and popped once, giving an amortized cost (average cost per operation over a sequence of operations) of O(log P) per scheduled payment. schedule_payment: O(log P) time, because validating the accounts takes O(1) and pushing the new tuple onto the min-heap takes O(log P).top_spenders: O(A log A) time, because we read each account's precomputedoutgoingcounter in O(1) and sort theAaccounts.get_history: O(H) time, because copying the account'sHhistory tuples prevents callers from mutating internal state.merge_accounts: O(H1 + H2 + P) time, whereH1andH2are the two accounts' history lengths; Python's built-in Timsort (an adaptive sorting algorithm that detects already-sorted runs and merges them in linear time) merges the two already-sorted history lists in O(H1 + H2) time, and scanning the heap to re-point pending payments takes O(P) time.- Space: O(A + total history entries + total scheduled payments), because we store one record per active account, every completed balance change in
history, and everyPaymentobject soget_payment_statusworks even after settlement.
Edge cases
- Failed operations leave zero trace: overdrafts, non-positive amounts, missing accounts, and self-transfers return
FalseorNonewithout adding any history entry or changingoutgoing. - Payment due at the exact operation timestamp:
due_time <= timestampsettles the payment before the operation runs, soaccept_paymentcalled atdue_timeseesEXPIREDand returnsFalse, anddepositcalled atdue_timearrives too late to save an underfunded payment. - Ties in due times: broken by
sequence_num(scheduling order), never by acceptance order or dictionary iteration order. - Ties and bounds in
top_spenders: equaloutgoingtotals break ties alphabetically byaccount_id; accounts with0outgoing are included;n > Areturns all accounts;n <= 0returns[]. - Merges and pending payments: a pending payment between
keep_idandother_idbecomes a self-payment and transitions toCANCELLED; recreatingother_idlater creates an empty account that does not inherit old pending payments.
Common mistakes
- Calling
_process_duemanually in only a few methods: forgetting it intop_spenders,create_account, ormerge_accountsexposes stale balances and stale rankings. Wrapping all public methods with one decorator eliminates this bug class. - Using
<instead of<=when popping due payments: a query att = 10then misses a payment due att = 10. - Recording
timestampinstead ofpayment.due_timein history: if a payment due at8is settled when a call arrives at12, stamping12corrupts chronological history order when accounts later merge. - Mutating before validating: debiting the source account before checking that
target_idexists andsource_id != target_iddestroys money on invalid calls. - Forgetting
n <= 0in Python slicing:ranked[:n]whenn = -1returns all accounts except the last instead of[]. - Not re-pointing pending payments during
merge_accounts: when those payments later come due,self._accounts[payment.source]either raisesKeyErroror charges a new account that reusedother_id.
Alternative approaches
- Explicit gate helper instead of a decorator: calling
self._process_due(timestamp)on the first line of each public method avoids decorator syntax and is equally fast, though someone adding a Level 5 method must remember to include the call. - Lazy deletion vs. eager removal on cancel: we use lazy deletion (marking a cancelled item inactive in place and ignoring it when the heap eventually pops it) instead of removing it from the middle of
_due, which keeps cancellation O(1) per affected payment without breaking the heap invariant.
Follow-up questions
- How would you support historical point-in-time queries asking for an account's balance at an arbitrary past timestamp T, even after scheduled settlements and account merges? Because every ledger tuple records a signed delta stamped with the exact moment money moved (
payment.due_timefor scheduled settlements), an account's balance atTequals the sum of signed deltas whoseentry_time <= T. Maintaining a parallel prefix sum array (a running cumulative balance alongside each ledger entry) lets binary search (repeatedly halving the sorted search window) find the rightmost entry<= Tin O(log H) time. If callers also need a merged-away account's pre-merge balance in isolation, tag each ledger entry with its originalaccount_idand store the merge timestamp. - What breaks if client requests can arrive with out-of-order timestamps, and how would you redesign the engine to handle late-arriving events? Eager settlement assumes time only advances; if a
depositstampedt = 5arrived after a payment att = 8had already transitioned toFAILEDfor low funds, that earlier failure decision would be invalid. To handle out-of-order arrivals, buffer incoming commands behind a watermark (a timestamp cutoff guaranteeing older requests are no longer accepted) and drain buffered commands strictly in timestamp order, or keep an ordered command log with periodic state snapshots and replay from the latest snapshot preceding any late event. - How would you add thread safety so multiple worker threads can invoke operations concurrently without race conditions or deadlocks? Because
_process_duemutates shared heap state and can touch arbitrary accounts, fine-grained per-account locks alone cannot protect the settlement step. The cleanest starting point acquires a single coarse-grained mutex inside the decorator—or serializes calls through a single-writer actor queue—and if multi-core scaling becomes necessary, shards accounts across partitions and coordinates cross-shard operations via a two-phase locking rule that acquires account locks in sorted ID order to prevent deadlocks. - Suppose
top_spendersis queried orders of magnitude more frequently than balances change. How would you optimize its latency? Store active accounts in a balanced search tree (an ordered structure such assortedcontainers.SortedListsupporting O(log A) inserts and deletes) keyed by(-outgoing, account_id): each outgoing transfer or settlement updates only the sender's tree position in O(log A) time, whiletop_spenders(n)iterates the firstnitems in O(n) time. Even simpler in pure standard library Python, cache the sorted ranking list and flip a booleandirtyflag whenever_move,create_account, ormerge_accountsmutates state so repeated reads between mutations slice the cached list in O(n) time.
Follow-up questions
- How would you support historical point-in-time queries asking for an account's balance at an arbitrary past timestamp T, even after scheduled settlements and account merges?
- What breaks if client requests can arrive with out-of-order timestamps, and how would you redesign the engine to handle late-arriving events?
- How would you add thread safety so multiple worker threads can invoke operations concurrently without race conditions or deadlocks?
- Suppose `top_spenders` is queried orders of magnitude more frequently than balances change. How would you optimize its latency?
Similar questions
- Points Ledger with Deferred Transfers
- In-Memory File Store with Quotas and Resizing
- High-Concurrency Account Ledger Service Design
- Staged File Storage with Quotas and Snapshots
- Bank Ledger with Delayed Payments and Account Consolidation
- Stateful Shift Hours and Compensation Ledger
More Airbnb interview questions
- Workspace Credit Ledger With Rankings and Scheduled Transfers Medium
- Stateful Credit Ledger with Delayed Transfers and Account Merges Medium
- Find Valid Split-Stay Listing Pairs Medium Pro
- Granular Project Review: Milestones, Architecture, and Impact Medium Pro
- Cross-Team Execution, Collaboration, and Core Values Hard Pro
- Compute City-Level Median Listing Prices Medium Pro
- In-Memory File Store with Quotas and Resizing Medium Pro
- Personalized Rental Search with User and Property Embeddings Medium Pro
- Classifying Kid-Suitable Vacation Rentals for Search Filtering Medium Pro
- Bank Ledger with Delayed Payments and Account Consolidation Medium Pro