KatInterview

Account Ledger with Reservation Expiry and Merging

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machinereservation-systemunion-find

Last updated

Design a banking ledger that supports deposits, time-limited transfer reservations, acceptance of reserved transfers, and merging accounts with their pending operations.

Problem

Design a ledger system for managing accounts with the following capabilities:

Operations:

  1. create_account(account_id): Initialize a new account starting at zero balance. Return True on success, False if that ID is already taken or was previously deleted.

  2. deposit(account_id, amount): Add funds to an existing account. Return the updated balance, or None if the account doesn't exist.

  3. request_transfer(from_id, to_id, amount, timestamp): Reserve funds for a future transfer. The sender must exist, have sufficient available balance (actual balance minus already-reserved amounts), and the recipient must exist. The reservation remains valid for 1000 time units; if not accepted by timestamp + 1000, it expires automatically. Return a unique reservation ID on success, None on failure.

  4. accept_transfer(reservation_id, current_timestamp): Finalize a reserved transfer. Deduct the amount from the sender, credit the recipient, and consume the reservation. Return True if successful, False if the reservation doesn't exist, has expired (current_timestamp > creation_timestamp + 1000), or was already used.

  5. merge_accounts(account_id1, account_id2): Consolidate account_id2 into account_id1. Transfer all funds and migrate all pending outgoing reservations. After merging, account_id2 is permanently deleted and cannot be recreated. Return True on success, False if either account is missing or if they're the same.

Rules:

  • All amounts and account IDs are positive integers.
  • Reservation IDs must be unique across the system's lifetime.
  • A reservation accepted at exactly timestamp + 1000 is still valid.
  • Self-transfers (sender equals recipient) should be rejected.
  • After a merge, old reservations referencing the deleted account should resolve to the surviving account.

Example:

ledger = AccountLedger()
ledger.create_account(1)           # True
ledger.deposit(1, 100)             # 100
ledger.request_transfer(1, 2, 50, 100)  # None (account 2 missing)
ledger.create_account(2)           # True
res = ledger.request_transfer(1, 2, 50, 100)  # returns reservation ID
ledger.accept_transfer(res, 500)   # True; balances: 1→50, 2→50

Hints

Hint 1

Track available balance separately from total balance by subtracting active reservation amounts.

Hint 2

Use path compression to resolve merged accounts efficiently when processing reservations.

Hint 3

Clean up expired reservations lazily when checking available balance or processing acceptance.