KatInterview

In-Memory Ledger with Ranking by Total Money Sent

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structure-designhash-mapheap

Last updated

Build an in-memory ledger supporting account creation, deposits and transfers, plus a query returning the top n senders by cumulative outgoing amount with deterministic tie-breaking.

Design and implement a small in-memory ledger for a bank. It must support these operations:

  1. createAccount(accountId, initialBalance = 0) registers a new account.
  2. deposit(accountId, amount) adds money to an existing account.
  3. transfer(fromId, toId, amount) moves money from one account to another. It must be rejected if the sender does not have enough funds.

For every account, track the total outgoing amount: the sum of all amounts that account has successfully sent through transfers.

Then implement topNAccountsByOutgoing(n). It returns the n accounts with the largest total outgoing amount. Ties are broken by accountId in ascending order. Each result is a string in the form "{outgoingAmount}:{accountId}".

What to deliver

  • The data structures you choose and why.
  • How you handle errors: unknown accounts, invalid amounts, duplicate accounts, insufficient funds, and anything else you consider relevant.
  • Pseudocode (or code) for two versions of the top-n query: one that sorts all accounts, and one that uses a heap of size n.
  • Time and space complexity of every operation.
  • A short discussion of how you would adapt the design if the ranking query were called very frequently.

Hints

Hint 1

Decide the contract before coding: integer amounts, which values are valid, what each method returns on failure, and whether a transfer to oneself is allowed. Counting only successful transfers toward outgoing totals keeps the numbers consistent.

Hint 2

A hash map from account id to a small record holding `balance` and `outgoing` gives O(1) updates. Update `outgoing` incrementally inside `transfer` rather than recomputing it from a history.

Hint 3

Validate everything first, then mutate. A transfer should never change the sender and then fail on the receiver.

Hint 4

For the heap version, keep a min-heap of size n whose root is the worst candidate so far. 'Worst' means smallest outgoing, and on equal outgoing, the largest id. Pop whenever the size exceeds n.