KatInterview

In-Memory Transaction Ledger with Aliases and History

Data Structure DesignModel answer
HardModel answerData Structure Designunion-findheapbinary-search

Last updated

Implement a timestamped in-memory ledger supporting deposits, cashback transfers, scheduled execution, account merging with alias resolution, and point-in-time balance queries.

In-Memory Transaction Ledger

You are building a simplified in-memory financial ledger. Implement a class MoneyLedger that tracks account balances over time. All method calls arrive with non-decreasing timestamps.


Methods

open_account(account_id: str) -> bool Opens a new account with a starting balance of 0. Returns False if account_id already exists or is a known alias of another account. Returns True on success. This method takes no timestamp.


deposit(timestamp: int, account_id: str, amount: int) -> int | None Adds amount to the account. Returns the new balance, or None if the account does not exist or amount <= 0.


transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> bool Moves amount from source_id to target_id. On success:

  • Deducts amount from the sender.
  • Credits amount to the receiver.
  • Immediately credits a cashback of (amount * 2) // 100 back to the sender (integer floor division).
  • Returns True.

Returns False if either account does not exist, amount <= 0, the two IDs resolve to the same account (including through aliases), or the sender's balance is less than amount.


queue_transfer(timestamp: int, job_id: str, source_id: str, target_id: str, amount: int, run_at: int) -> bool Schedules a transfer to execute at time run_at, where run_at > timestamp. Returns False if job_id has already been used (even for a completed job). Does not check or reserve funds at scheduling time. Returns True if the job is queued successfully.


merge_accounts(timestamp: int, primary_id: str, secondary_id: str) -> bool Absorbs secondary_id into primary_id. All funds in secondary_id move to primary_id. From this point on, any operation that references secondary_id automatically targets primary_id instead. Returns False if either account does not exist or both IDs already resolve to the same account. Returns True on success.


balance_at(timestamp: int, account_id: str, when: int | None = None) -> int | None Returns the balance for account_id. If when is None, returns the current balance as of timestamp. If when is provided, returns the balance immediately after all transactions at or before when were applied. Returns None if account_id does not exist.


top_senders(timestamp: int, k: int) -> list[str] Returns the k account IDs with the highest total gross outgoing transfer amounts. Gross outgoing means the full amount sent, before cashback. Ties are broken by lexicographic order of the canonical account ID (ascending).


Scheduling Rules

Before processing any timestamped method at time T, the ledger must first execute all queued transfers whose run_at <= T, in ascending order of run_at. When two jobs share the same run_at, execute them in lexicographic order of job_id. A job that fails at execution time (insufficient funds, missing account, same-account resolution) is discarded silently and never retried.


Example

ledger = MoneyLedger()
ledger.open_account("alice")          # True
ledger.open_account("bob")            # True

ledger.deposit(1, "alice", 1000)      # 1000
ledger.queue_transfer(2, "j1", "alice", "bob", 500, 10)   # True
ledger.transfer(5, "alice", "bob", 200)
# alice: 1000 - 200 + 4 cashback = 804. bob: 200.
# Returns True

ledger.balance_at(10, "alice")
# Before answering, j1 runs: alice sends 500, gets 10 cashback.
# alice: 804 - 500 + 10 = 314. bob: 700.
# Returns 314

ledger.top_senders(10, 1)             # ["alice"] (gross sent: 200 + 500 = 700)

ledger.merge_accounts(12, "bob", "alice")
# True. bob now has 700 + 314 = 1014. "alice" is an alias for "bob".

ledger.deposit(15, "alice", 100)      # 1114  (alias resolves to bob)
ledger.balance_at(15, "bob")          # 1114
ledger.balance_at(15, "alice", when=1)  # 1000  (alice's historical balance at t=1)

Constraints

  • 1 <= timestamp, non-decreasing across calls.
  • 1 <= amount <= 10^9 for all financial operations.
  • 1 <= k <= number of accounts.
  • run_at > timestamp at scheduling time.
  • Account IDs and job IDs consist of lowercase letters and digits.
  • Up to 5 × 10^4 total method calls.

Hints

Hint 1

Before implementing anything else, think about how to drain the scheduled-job queue. Every timestamped method must do this first. A min-heap keyed on (run_at, job_id) gives you the right execution order with no extra sorting.

Hint 2

Account merging needs two separate structures: a union-find (with path compression) for fast current-time resolution, and a separate append-only map from each merged ID to (merge_timestamp, canonical_target). Path compression destroys the merge history, which is why you can't rely on it alone for historical queries.

Hint 3

For point-in-time balance lookups, store per-account parallel lists of (timestamp, balance_after_change). A bisect_right search finds the right snapshot in O(log H). For historical queries on a merged account, walk the merge-history chain stopping at the first merge whose timestamp is strictly after `when`.