In-Memory Ledger with Ranking by Total Money Sent
Data Structure DesignModel answerLast 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:
createAccount(accountId, initialBalance = 0)registers a new account.deposit(accountId, amount)adds money to an existing account.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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
This is mostly an API and correctness exercise. A strong answer has four parts: a clear contract, atomic state changes, explicit error handling, and a top-n query whose cost you can reason about.
1. Clarify the contract
- Money as integers. Use the smallest currency unit (cents). Floating point introduces rounding errors.
- Valid inputs.
initialBalance >= 0.depositandtransferamounts must be strictly positive. - Return values. Mutations report failure instead of throwing, so callers can branch easily:
createAccountreturns a boolean,depositreturns the new balance orNone, andtransferreturns a boolean. - Self-transfer. Reject
fromId == toId. It would raise the outgoing total without moving any money. - Outgoing definition. Only successful transfers count, and only for the sender. Deposits and rejected transfers do not.
- Top-n. If
nexceeds the number of accounts, return them all. Ifn <= 0, return an empty list. Accounts with zero outgoing are still ranked, ordered by id. - Id ordering. Plain string comparison, so
"acc10" < "acc2". State this and ask whether numeric order is wanted.
2. Data structures
accounts: HashMap<String, Account>
Account { balance: int, outgoing: int }
The hash map gives O(1) average lookup for all mutations. Storing outgoing on the account and updating it in transfer avoids rescanning history. An append-only transaction log is a reasonable add-on for auditing but is not needed for the queries.
3. Error handling
| Condition | Behavior |
|---|---|
| Duplicate id on create | return false, no change |
| Negative initial balance | return false |
| Unknown account in deposit or transfer | fail, no change |
| Amount <= 0 | fail, no change |
fromId == toId | fail, no change |
| Insufficient funds | fail, balances and outgoing untouched |
Draining a balance to exactly zero is legal. Only a strictly insufficient balance is rejected. A deposit to an unknown account fails rather than creating the account silently.
The key property is atomicity: check every precondition, then apply the debit, credit and outgoing update together. In a single-threaded model that is enough. If concurrency matters, mention a lock per account taken in a consistent order (for example sorted by id) to avoid deadlock, or a single global lock for simplicity.
4. Top-n by sorting
topN_sort(n):
if n <= 0: return []
items = [(acc.outgoing, id) for id, acc in accounts]
sort items by (-outgoing, id)
return [f"{o}:{id}" for (o, id) in items[:n]]
5. Top-n with a heap
Keep a min-heap of at most n entries where the root is the worst candidate: lowest outgoing, and among equal outgoing, the largest id.
topN_heap(n):
if n <= 0: return []
heap = empty min-heap with order "worse is smaller"
for (id, acc) in accounts:
push (acc.outgoing, id)
if size(heap) > n: pop root
result = pop everything, then reverse
return formatted result
Strings cannot be negated, so the reversed id tie-break needs a small wrapper class with a custom __lt__, or you can use heapq.nsmallest with a composite key. Because ids are unique the ordering is a strict total order, so results are deterministic.
6. Reference code
import heapq
class _Acc:
__slots__ = ("balance", "outgoing")
def __init__(self, b): self.balance = b; self.outgoing = 0
class _Worst:
__slots__ = ("o", "i")
def __init__(self, o, i): self.o = o; self.i = i
def __lt__(self, other):
if self.o != other.o:
return self.o < other.o
return self.i > other.i # larger id is worse
class Bank:
def __init__(self): self.a = {}
def createAccount(self, aid, initial=0):
if aid in self.a or initial < 0: return False
self.a[aid] = _Acc(initial); return True
def deposit(self, aid, amount):
acc = self.a.get(aid)
if acc is None or amount <= 0: return None
acc.balance += amount
return acc.balance
def transfer(self, f, t, amount):
if f == t or amount <= 0: return False
s, d = self.a.get(f), self.a.get(t)
if s is None or d is None or s.balance < amount: return False
s.balance -= amount; d.balance += amount; s.outgoing += amount
return True
def topN_sort(self, n):
if n <= 0: return []
items = sorted(((x.outgoing, k) for k, x in self.a.items()),
key=lambda t: (-t[0], t[1]))
return [f"{o}:{k}" for o, k in items[:n]]
def topN(self, n):
if n <= 0: return []
h = []
for k, x in self.a.items():
heapq.heappush(h, _Worst(x.outgoing, k))
if len(h) > n: heapq.heappop(h)
out = []
while h:
e = heapq.heappop(h)
out.append(f"{e.o}:{e.i}")
out.reverse()
return out
7. Why it is correct
- Balances. Each transfer validates before mutating, and the debit and credit happen together, so total money is conserved.
- Outgoing. It changes in exactly one place, by exactly the debited amount, so it equals the sum of that account's successful debits.
- Heap invariant. After any prefix of accounts, the heap holds the best
min(n, seen)of them. A new item either displaces the root or is itself evicted.
8. Complexity
With m accounts:
| Operation | Time | Extra space |
|---|---|---|
| create, deposit, transfer | O(1) average | O(1) |
| top-n by sort | O(m log m) | O(m) |
| top-n by heap | O(m log n) | O(n) |
| Total storage | O(m) |
The heap is better when n is much smaller than m. For n close to m the difference is negligible and sorting is simpler.
9. Follow-ups
- Frequent queries. Maintain an ordered index (balanced BST or a sorted container) keyed by
(-outgoing, id). A transfer removes and reinserts the sender's key in O(log m), and a query reads the firstnentries in O(n + log m). This moves cost from reads to writes, so the right choice depends on the read/write ratio. - Very large
m, very smalln. Quickselect gives O(m) average but is harder to keep deterministic for ties. - Persistence and audit. Write an append-only log of operations and rebuild state by replay.
Common mistakes
- Using floats for money.
- Counting rejected transfers or deposits toward outgoing.
- Allowing self-transfers.
- Debiting before checking that the receiver exists.
- Getting the heap comparator backwards on ties, so the wrong id is evicted.
- Forgetting accounts with zero outgoing, or mishandling
nlarger than the account count.