KatInterview

Simulate a Stateful Banking Ledger with Queued Payments

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designheaphash-tablesimulation

Last updated

Simulate an in-memory banking system handling accounts, balances, scheduled payments via a priority queue, and account merges.

Implement a simulation function run_bank_system that processes a sequence of timestamped operations for an in-memory financial ledger.

Every operation carries an integer timestamp t. Timestamps across calls are non-decreasing. Before carrying out the operation at time t, the ledger must first execute all queued scheduled payments whose scheduled trigger time is less than or equal to t.

Scheduled Payment Execution Order & Rules

  1. Process due payments in ascending order of scheduled execution time (timestamp + delay).
  2. If multiple payments have the exact same execution time, resolve ties alphabetically (lexicographically) by their payment identifier string payment_id.
  3. To execute a payment, verify:
    • Both the current source account and current destination account are active.
    • The current source account ID is distinct from the current destination account ID.
    • The current source account has a balance $\ge$ payment amount.
  4. If valid, deduct the amount from the source, add it to the destination, and increase the source's cumulative lifetime outgoing spending counter by amount. Mark the payment as completed.
  5. If invalid (e.g. insufficient funds, deactivated account, or source and target became identical), the payment fails silently and is permanently discarded (marked as completed without transferring funds).
  6. A scheduled payment processes at most once.

Operations

Each operation is represented by a command string in operations and a matching parameter list in arguments (where args[0] is always timestamp):

  • "create_account": [timestamp, account_id]

    • Registers a new active account with balance 0 and spending 0.
    • Returns True if created. Returns False if account_id is currently an active account.
  • "deposit": [timestamp, account_id, amount]

    • Adds amount to account_id.
    • Returns the updated integer balance, or None if account_id is not active.
  • "transfer": [timestamp, src_id, dest_id, amount]

    • Immediately transfers amount from src_id to dest_id.
    • Succeeds if both accounts are active, src_id != dest_id, and src_id's balance is $\ge$ amount.
    • On success, increases src_id's cumulative outgoing spending by amount and returns True. Otherwise returns False.
  • "top_spenders": [timestamp, n]

    • Returns a list of up to n active account IDs sorted by total cumulative outgoing transfer spending in descending order.
    • Ties in spending are broken alphabetically by account_id.
    • If n <= 0, returns []. Accounts with zero spending are included if space permits.
  • "schedule_payment": [timestamp, payment_id, src_id, dest_id, amount, delay]

    • Schedules a future transfer to execute at timestamp + delay.
    • Returns True if payment_id has never been used before, both src_id and dest_id are currently active, src_id != dest_id, and amount > 0. Returns False otherwise.
  • "cancel_payment": [timestamp, payment_id]

    • Cancels a pending scheduled payment.
    • Returns True if payment_id exists and is currently pending. Returns False if it does not exist, was already cancelled, or already executed.
  • "merge_accounts": [timestamp, target_id, source_id]

    • Merges source_id into target_id.
    • Succeeds only if both target_id and source_id are active and target_id != source_id. Returns False if invalid.
    • On success:
      1. Transfers all current balance and lifetime spending from source_id into target_id.
      2. Updates all pending scheduled payments where source_id appears as source or destination so they point to target_id instead.
      3. Deactivates source_id (it can later be re-created via "create_account" as a fresh account).
      4. Returns True.

Constraints

  • $1 \le \text{timestamp} \le 10^9$, non-decreasing across sequence.
  • $1 \le \text{amount}, \text{delay} \le 10^9$.
  • Account and payment IDs are non-empty strings of alphanumeric characters ($\le 32$ chars).
  • Total operation count $\le 10^4$.

Examples

Example 1

Input: run_bank_system(['create_account', 'create_account', 'deposit', 'schedule_payment', 'transfer', 'top_spenders', 'deposit', 'top_spenders'], [[1, 'A'], [1, 'B'], [2, 'A', 100], [3, 'p1', 'A', 'B', 40, 5], [4, 'A', 'B', 20], [5, 2], [8, 'B', 10], [9, 1]])

Output: [True, True, 100, True, True, ['A', 'B'], 70, ['A']]

Hints

Hint 1

Flush all scheduled payments with execution_time <= current timestamp before handling the current command.

Hint 2

Maintain a min-heap storing tuples of (execution_time, payment_id) for scheduled tasks to efficiently retrieve due payments in order.

Hint 3

Use a status flag ('pending', 'cancelled', 'finished') for each payment to easily handle cancellations without needing to delete elements from middle of the min-heap.

Hint 4

When merging accounts, rewrite the source and destination fields of all currently pending payments.