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: Creates account_id with balance 0, outgoing total 0, and an empty ledger, returning True. Returns False if account_id already exists.
  • deposit(timestamp: int, account_id: str, amount: int) -> Optional[int]: Adds amount to account_id, appends (timestamp, "deposit", amount) to its ledger, and returns the updated balance. Returns None if account_id does not exist or amount <= 0.
  • transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: Moves amount from source_id to target_id, increases source_id's outgoing total by amount, appends (timestamp, "transfer_out", -amount) to source_id's ledger and (timestamp, "transfer_in", amount) to target_id's ledger, and returns source_id's new balance. Returns None if either account is missing, source_id == target_id, amount <= 0, or source_id's balance is less than amount.
  • get_balance(timestamp: int, account_id: str) -> Optional[int]: Returns the current balance of account_id, or None if account_id does not exist.
  • get_history(timestamp: int, account_id: str) -> Optional[List[Tuple[int, str, int]]]: Returns account_id's completed balance changes as [(entry_timestamp, kind, signed_amount), ...] from oldest to newest, or None if account_id does 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 (A to Z) by account_id, and returns up to n pairs (account_id, outgoing_total).
    • Outgoing total equals the sum of completed transfer amounts sent plus "EXECUTED" scheduled payment amounts sent (deposits, incoming funds, and unexecuted payments never count).
    • Accounts with 0 outgoing total are included. If n exceeds the number of active accounts, return all active accounts; if n <= 0, return [].

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 of amount from source_id to target_id due at due_time = timestamp + delay with initial status "SCHEDULED". Valid calls return sequential IDs "payment1", "payment2", ... (rejected calls do not advance the counter). Returns None if either account is missing, source_id == target_id, amount <= 0, or delay <= 0. Funds are verified only at due_time.
  • accept_payment(timestamp: int, account_id: str, payment_id: str) -> bool: If payment_id exists, its status is still "SCHEDULED" (meaning timestamp < due_time), and account_id equals the designated recipient target_id, updates status to "ACCEPTED" and returns True; otherwise returns False.
  • Settlement at due_time:
    • "SCHEDULED" (never accepted before due_time) transitions to "EXPIRED" without moving funds.
    • "ACCEPTED" checks the payer's balance at due_time: if < amount, status transitions permanently to "FAILED" with no retry; otherwise amount moves from payer to recipient, payer's outgoing total increases by amount, ledger entries (due_time, "payment_out", -amount) and (due_time, "payment_in", amount) are recorded using due_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", or None if payment_id is unknown.

Stage 4 — Account Consolidation

  • merge_accounts(timestamp: int, keep_id: str, other_id: str) -> bool: Absorbs other_id into keep_id and returns True, or returns False if keep_id == other_id or either account does not exist.
    • keep_id's balance and outgoing total each increase by other_id's values, and both ledgers are combined in chronological order.
    • other_id ceases to exist (create_account may later reuse other_id as a fresh empty account).
    • Any pending ("SCHEDULED" or "ACCEPTED") payment referencing other_id as payer or recipient is re-pointed to keep_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

  • timestamp is an integer arriving in non-decreasing order across calls (timestamp < previous_timestamp raises ValueError).
  • account_id is a string; amount, delay, and n are integers.
  • Valid deposit, transfer, and schedule_payment calls require amount > 0 (and delay > 0 for schedule_payment).
  • Up to 10^4 total operations across accounts, transfers, scheduled payments, leaderboard queries, and merges.

Step-by-step walkthrough

  1. 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 timestamp first. If timestamp is smaller than the previous call's timestamp, raise ValueError immediately.
    • All-or-nothing validation: an invalid call returns False or None and 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 <= timestamp runs before the operation at timestamp. If two payments share the same due_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) True False if id already exists
    deposit(ts, id, amount) new balance None if missing account or amount <= 0
    transfer(ts, src, dst, amount) src's new balance None if missing account, src == dst, amount <= 0, or insufficient funds
    get_balance(ts, id) / get_history(ts, id) balance / [(ts, kind, signed_amount), ...] None if missing account
    top_spenders(ts, n) [(id, outgoing_total), ...] [] if n <= 0
    schedule_payment(ts, src, dst, amount, delay) "payment1", "payment2", ... None if missing account, src == dst, amount <= 0, or delay <= 0
    accept_payment(ts, id, payment_id) True False if unknown, id is not recipient, or status is not SCHEDULED
    get_payment_status(ts, payment_id) status string None if unknown
    merge_accounts(ts, keep_id, other_id) True False if keep_id == other_id or either account is missing
  2. Design the Account and Payment records

    Ask what each account needs to remember across all four levels:

    1. balance: current integer funds.
    2. outgoing: a running total of money sent out. Updating one integer whenever money moves takes O(1) time and avoids rescanning full transaction histories during top_spenders.
    3. history: a list of (timestamp, kind, signed_amount) tuples in chronological order. Storing signed amounts (+100 for deposits, -70 for 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 Payment object so Level 3 can look up its status by ID and Level 4 can rewrite its source or target when 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 = SCHEDULED
    
  3. Settle due payments before every operation

    Suppose a payment is due at t = 10, and no caller talks to the bank between t = 6 and t = 12. When get_balance(12, "A") or top_spenders(12, 3) arrives, the bank must first catch up to t = 12 by settling the payment at t = 10.

    To find due payments quickly and in deterministic order, store pending payments in a min-heap _due of (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_payments decorator:

    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
    

    Inside _process_due, check timestamp ordering first, then pop and settle while due_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)
    
  4. Implement Level 1: accounts, deposits, and transfers

    Every mutating method validates all preconditions before touching any balance or history. Both transfer and executed scheduled payments move money between two accounts in the exact same way, so extract a _move helper that updates source.balance, source.outgoing, target.balance, and both history lists together. In get_history, return list(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)
    
  5. Implement Level 2: rank top spenders

    Because _move keeps account.outgoing up to date on every outgoing transfer and executed payment, top_spenders only needs to sort the existing accounts and take the first n.

    Negating account.outgoing in the sort key (-account.outgoing, account.account_id) places higher spenders first while breaking ties alphabetically ("a" before "b"). Check n <= 0 explicitly 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 result
    
    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)
    
  6. 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 before due_time. Reject delay <= 0 because a scheduled payment must lie strictly in the future so the recipient has a chance to accept it.

    Notice two subtle details in _settle and accept_payment:

    • Because @processes_due_payments runs before accept_payment, calling accept_payment at timestamp == due_time finds the payment already popped and marked EXPIRED, so payment.status != SCHEDULED cleanly returns False.
    • When an ACCEPTED payment executes, _move is called with payment.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
    
  7. Implement Level 4: merge accounts and trace a full timeline

    When merge_accounts(ts, keep_id, other_id) runs, trace every place other_id can live:

    1. _accounts[other_id]: pop it so other_id disappears (and can later be recreated from scratch).
    2. balance, outgoing, and history: add other's totals into keep and merge both history lists sorted by timestamp.
    3. Pending payments inside self._due: rewrite payment.source and payment.target from other_id to keep_id. If a pending payment was between keep_id and other_id, both endpoints are now keep_id; mark it CANCELLED and 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 True
    
    def _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 at t = 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=75
    
  8. Complete 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:

  1. t = 2: deposit("kai", 120) sets kai.balance = 120.
  2. t = 3: schedule_payment("kai", "ava", 75, delay=7) pushes (due=10, seq=1, "payment1") onto the min-heap with status SCHEDULED.
  3. t = 7: accept_payment("ava", "payment1") flips status to ACCEPTED (no money moves yet).
  4. t = 11: top_spenders(11, 2) arrives. Before sorting accounts, the decorator pops "payment1" (since 10 <= 11), sees kai.balance >= 75, moves 75 from "kai" to "ava" stamped at time 10, and adds 75 to kai.outgoing—so top_spenders immediately 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 when k payments come due at once, because popping each due item from the min-heap of size P takes 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 precomputed outgoing counter in O(1) and sort the A accounts.
  • get_history: O(H) time, because copying the account's H history tuples prevents callers from mutating internal state.
  • merge_accounts: O(H1 + H2 + P) time, where H1 and H2 are 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 every Payment object so get_payment_status works even after settlement.

Edge cases

  • Failed operations leave zero trace: overdrafts, non-positive amounts, missing accounts, and self-transfers return False or None without adding any history entry or changing outgoing.
  • Payment due at the exact operation timestamp: due_time <= timestamp settles the payment before the operation runs, so accept_payment called at due_time sees EXPIRED and returns False, and deposit called at due_time arrives 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: equal outgoing totals break ties alphabetically by account_id; accounts with 0 outgoing are included; n > A returns all accounts; n <= 0 returns [].
  • Merges and pending payments: a pending payment between keep_id and other_id becomes a self-payment and transitions to CANCELLED; recreating other_id later creates an empty account that does not inherit old pending payments.

Common mistakes

  • Calling _process_due manually in only a few methods: forgetting it in top_spenders, create_account, or merge_accounts exposes 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 at t = 10 then misses a payment due at t = 10.
  • Recording timestamp instead of payment.due_time in history: if a payment due at 8 is settled when a call arrives at 12, stamping 12 corrupts chronological history order when accounts later merge.
  • Mutating before validating: debiting the source account before checking that target_id exists and source_id != target_id destroys money on invalid calls.
  • Forgetting n <= 0 in Python slicing: ranked[:n] when n = -1 returns 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 raises KeyError or charges a new account that reused other_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_time for scheduled settlements), an account's balance at T equals the sum of signed deltas whose entry_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 <= T in O(log H) time. If callers also need a merged-away account's pre-merge balance in isolation, tag each ledger entry with its original account_id and 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 deposit stamped t = 5 arrived after a payment at t = 8 had already transitioned to FAILED for 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_due mutates 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_spenders is 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 as sortedcontainers.SortedList supporting 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, while top_spenders(n) iterates the first n items in O(n) time. Even simpler in pure standard library Python, cache the sorted ranking list and flip a boolean dirty flag whenever _move, create_account, or merge_accounts mutates state so repeated reads between mutations slice the cached list in O(n) time.

Follow-up questions

Similar questions

More Airbnb interview questions

All 112 Airbnb questions →