KatInterview

Stateful Banking System Ledger Engine

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designdesign-dsheaps-sortingarrays

Last updated

Simulate an in-memory banking ledger that processes chronologically ordered operations involving balances, leaderboards, delayed cashbacks, and account merges.

Design an in-memory banking engine that processes a stream of chronological financial queries and produces a list of string outcomes, one per query.

Each request in queries is an array of strings formatted as follows:

  • Index 0: Operation name string.
  • Index 1: A timestamp (integer formatted as a string, in milliseconds, strictly increasing across queries).
  • Subsequent indices: Operation arguments.

Numerical outputs should not contain any currency symbols or thousands separators. Return "" (empty string) whenever an operation fails or is invalid, unless specified otherwise.


Supported Operations

1. Core Accounts

  • ["CREATE_ACCOUNT", timestamp, account_id]
    • Registers a new account. Returns "true" on success, or "false" if account_id already exists.
  • ["DEPOSIT", timestamp, account_id, amount]
    • Adds amount to account_id. Returns the updated balance as a string, or "" if account_id does not exist.
  • ["GET_BALANCE", timestamp, account_id]
    • Returns the current balance of account_id as a string, or "" if account_id does not exist.

2. Transfers & Leaderboards

  • ["TRANSFER", timestamp, source_id, target_id, amount]
    • Transfers amount from source_id to target_id. Returns the new balance of source_id as a string.
    • Returns "" if either account is missing, if source_id == target_id, or if source_id has insufficient funds (no transfer occurs in these cases).
  • ["TOP_SPENDERS", timestamp, n]
    • Returns a formatted string listing the top n active accounts sorted by total outgoing funds (the aggregate of all successful TRANSFER and PAY amounts originating from that account).
    • Format: "id1(total1), id2(total2)".
    • Tie-breaker: Sort primarily by total outgoing funds descending, then by account_id in ascending lexicographical order.
    • Includes all active accounts. If fewer than n active accounts exist, includes all of them.

3. Payments & Deferred Cashbacks

  • ["PAY", timestamp, account_id, amount]
    • Immediately deducts amount from account_id and generates a global payment identifier ("payment1", "payment2", … incremented on each successful payment). Returns the payment ID string.
    • Returns "" if the account does not exist or has insufficient funds.
    • Each payment earns 2% cashback calculated via integer division: $\lfloor \text{amount} \times 2 / 100 \rfloor$.
    • The cashback is automatically credited back to the account exactly 86400000 ms (24 hours) after the payment timestamp.
  • ["GET_PAYMENT_STATUS", timestamp, account_id, payment_id]
    • Returns "IN_PROGRESS" if the cashback has not yet been processed at timestamp, or "CASHBACK_RECEIVED" if it has been credited.
    • Returns "" if account_id does not exist or if payment_id was not created by (or inherited by) that account.

Cashback Processing Rule: Before processing any query at time $t$, all pending cashbacks scheduled at timestamps $\le t$ must be settled and credited to their respective target accounts.

4. Account Merging

  • ["MERGE_ACCOUNTS", timestamp, account_id_1, account_id_2]
    • Merges account_id_2 into account_id_1. Returns "true" on success, or "false" if either account does not exist or if account_id_1 == account_id_2.
    • Merging combines balances and cumulative spending totals into account_id_1. Any pending cashbacks owed to account_id_2 will be credited to account_id_1 upon maturity.
    • After merging, account_id_2 is removed from active accounts. However, subsequent GET_PAYMENT_STATUS queries for payments originally made by account_id_2 must succeed when queried against account_id_1.

Constraints

  • $1 \le \text{len(queries)} \le 10^4$
  • Timestamps are strictly increasing integers in the range $[1, 10^{15}]$.
  • All monetary amounts are non-negative integers in the range $[0, 10^9]$.
  • All account IDs are non-empty strings.

Examples

Example 1

Input: banking_system_simulation([['CREATE_ACCOUNT', '1', 'alice'], ['CREATE_ACCOUNT', '2', 'bob'], ['DEPOSIT', '3', 'alice', '2000'], ['TRANSFER', '4', 'alice', 'bob', '500'], ['TOP_SPENDERS', '5', '2'], ['PAY', '6', 'alice', '1000'], ['GET_PAYMENT_STATUS', '7', 'alice', 'payment1'], ['GET_PAYMENT_STATUS', '86400007', 'alice', 'payment1'], ['GET_BALANCE', '86400008', 'alice']])

Output: ['true', 'true', '2000', '1500', 'alice(500), bob(0)', 'payment1', 'IN_PROGRESS', 'CASHBACK_RECEIVED', '520']

Hints

Hint 1

Use a min-heap to keep track of pending cashbacks sorted by their maturity timestamp.

Hint 2

Process all pending cashbacks from the min-heap whose maturity time is less than or equal to the current operation's timestamp before processing the operation.

Hint 3

Use a Disjoint Set Union (DSU) structure to model merged accounts. This allows pending cashbacks and old payment records to dynamically resolve to the new combined account.