Design an In-Memory Ledger with Transfers and Activity Ranking
Data Structure DesignModel answerLast updated
Build an in-memory account ledger in stages—create/deposit, transfer, top-N by activity—plus a command-string test harness with clear failure semantics.
Context
You are asked to build an in-memory banking ledger as a class, incrementally, in a single interview slot. The work comes in four stages: basic accounts and deposits, transfers, a "most active accounts" ranking, and finally a small harness that runs table-driven test cases made of string commands against a fresh instance of your class.
This is a whiteboard/verbal round: you write code (or pseudocode with real signatures) and talk through the design. Explain your reasoning as you go, state assumptions out loud, and call out complexity. The harness is expected to be a real deliverable, not an afterthought—budget roughly a third of the time for it.
Ground rules
- Everything lives in memory. No persistence, no networking, single-threaded.
- Account IDs are non-empty strings; you may reject empty or duplicate IDs.
- Amounts are integers in the smallest currency unit. Do not use floating point for money.
- Command names and output strings are whatever the test data expects; the examples here are illustrative—confirm the exact format with your interviewer before hardcoding.
Clarify before coding
- What does each operation return on success, and how are failures reported (exception vs. error value vs. sentinel string)?
- Are zero or negative amounts rejected, and is that per operation or a general rule?
- Is transferring from an account to itself legal? Is it a no-op or an error?
- For the ranking: is "activity" the count of operations, the summed amount moved, or something else? Do both the sender and receiver of a transfer earn credit? Do failed operations or account creation count?
Part 1 — Accounts and deposits
Implement create_account(account_id) and deposit(account_id, amount).
- Creating an account that already exists must fail; on success the balance is 0.
- Depositing to a missing account must fail; on success return the new balance.
- Both operations should be O(1) average.
Part 2 — Transfers
Implement transfer(source_id, target_id, amount), which moves money between two existing accounts and returns the source's new balance.
- Fail if either account is missing, if the amount is invalid, or if the source has insufficient funds.
- A failure must leave both balances untouched (validate everything before mutating).
- Decide and justify the self-transfer behavior.
- Extend the Part 1 design rather than rewriting it.
Part 3 — Top activity
Implement top_activity(n), returning the n most active accounts, most active first, as a list of (account_id, activity) pairs or formatted strings.
- The definition of activity must be confirmed with the interviewer and then maintained incrementally (not recomputed from a log).
- Ties must resolve deterministically—state the rule.
- If
nexceeds the number of accounts, return all of them.
Part 4 — Test harness
Write a runner that takes a test (a list of operations, each a string array whose first element is the command name), creates a fresh ledger instance, dispatches each operation, and produces one output string per operation in order. Example input:
[["CREATE_ACCOUNT","acc1"],
["CREATE_ACCOUNT","acc2"],
["DEPOSIT","acc1","500"],
["TRANSFER","acc1","acc2","200"],
["TOP_ACTIVITY","2"]]
Dispatch must be easy to extend with new commands, output formatting must be consistent (including failures), and when actual output differs from expected output you should report which operation index and which command failed.
Hints
Hint 1
Pin down the meaning of 'activity' and the return/failure format before writing Part 3 and Part 4 code—these choices ripple back into every method signature.
Hint 2
Keep an accounts map from ID to a small record (balance + activity counter). For ranking, either sort a snapshot or use a bounded min-heap when n is much smaller than the number of accounts; a full sort is usually fine for interview scale.
Hint 3
In the harness, use a table mapping command name to a handler, parse integers in one place, and wrap each call so an exception becomes an error string instead of crashing the run.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
How I'd approach it
I'd start by locking down the contract, because every later stage depends on it. My defaults: methods throw a typed error (or return a documented error value) on failure; successful deposit/transfer return the resulting balance; create_account returns nothing or a boolean; amounts must be strictly positive integers (zero and negatives rejected); self-transfer is an error rather than a silent no-op, because it signals a caller bug and returning "success" hides it—though I'd flag that this is a decision the interviewer may want reversed. Activity I'd define as number of successful operations touching the account, with transfers crediting both sides and failed calls counting for nothing; creation may or may not count, so I'd ask. I'd also ask whether ranking returns pairs or formatted strings.
Data model
class LedgerError(Exception): pass
class Account:
__slots__ = ("balance", "activity")
def __init__(self):
self.balance = 0
self.activity = 0
class Ledger:
def __init__(self):
self.accounts = {} # id -> Account
A dict gives O(1) average lookup; __slots__ is a micro-optimization I'd mention but not insist on. Money is int throughout.
Part 1
class Ledger:
def create_account(self, account_id):
if not account_id:
raise LedgerError("EMPTY_ID")
if account_id in self.accounts:
raise LedgerError(f"ACCOUNT_EXISTS:{account_id}")
self.accounts[account_id] = Account()
def deposit(self, account_id, amount):
if amount <= 0:
raise LedgerError("INVALID_AMOUNT")
acct = self.accounts.get(account_id)
if acct is None:
raise LedgerError(f"ACCOUNT_NOT_FOUND:{account_id}")
acct.balance += amount
acct.activity += 1 # assuming deposits count as activity
return acct.balance
Both are O(1) average, O(1) space per account. Validating the amount first means a bad deposit on a missing account reports the more fundamental problem; either order is defensible as long as it's consistent and documented.
Part 2
def transfer(self, src, dst, amount):
if amount <= 0:
raise LedgerError("INVALID_AMOUNT")
if src == dst:
raise LedgerError("SELF_TRANSFER")
a = self.accounts.get(src)
b = self.accounts.get(dst)
if a is None:
raise LedgerError(f"ACCOUNT_NOT_FOUND:{src}")
if b is None:
raise LedgerError(f"ACCOUNT_NOT_FOUND:{dst}")
if a.balance < amount:
raise LedgerError("INSUFFICIENT_FUNDS")
# all checks passed — now mutate atomically
a.balance -= amount
b.balance += amount
a.activity += 1
b.activity += 1
return a.balance
The key discipline is validate-then-mutate: every failure path exits before the first assignment, so balances can never be half-updated. This is what interviewers probe when they ask "what if the target account vanished mid-transfer?"—in a single-threaded, in-memory model it can't, and I'd say so explicitly rather than hedging. O(1) time and space.
Part 3
I maintain the activity counter incrementally in Parts 1–2, so top_activity is purely a query. Two options:
Sort a snapshot — O(A log A) where A is the number of accounts, O(A) extra space:
def top_activity(self, n):
if n <= 0:
return []
items = sorted(self.accounts.items(),
key=lambda kv: (-kv[1].activity, kv[0]))
return [(aid, acct.activity) for aid, acct in items[:n]]
Tie-break: ascending ID (lexicographic), which is deterministic and requires no extra bookkeeping. If n >= len(accounts), slicing naturally returns everything.
Bounded min-heap — O(A log min(n, A)) time, O(n) space, better when n is tiny relative to A. Sort key becomes (activity, reversed_id) so the heap keeps the worst of the best-n at the top.
For interview scale the sort is simpler and I'd default to it, then note that if top_activity were called constantly on a large account set, I'd keep a lazily rebuilt heap or a sorted structure maintained on updates—trading write cost for read speed.
Part 4 — Harness
A dispatch table keeps the runner honest and extensible:
def run_test(ops, expected=None):
ledger = Ledger()
out, errors = [], []
def do_create(a): ledger.create_account(a[1]); return "OK"
def do_deposit(a): return str(ledger.deposit(a[1], int(a[2])))
def do_transfer(a): return str(ledger.transfer(a[1], a[2], int(a[3])))
def do_top(a):
res = ledger.top_activity(int(a[1]))
return "[" + ", ".join(f"{aid}={act}" for aid, act in res) + "]"
handlers = {"CREATE_ACCOUNT": do_create, "DEPOSIT": do_deposit,
"TRANSFER": do_transfer, "TOP_ACTIVITY": do_top}
for i, op in enumerate(ops):
try:
line = handlers[op[0]](op)
except KeyError:
line = f"ERROR:UNKNOWN_COMMAND:{op[0]}"
except LedgerError as e:
line = f"ERROR:{e}"
except (IndexError, ValueError):
line = "ERROR:MALFORMED_INPUT"
out.append(line)
if expected is not None and i < len(expected) and line != expected[i]:
errors.append(f"op {i} {op[0]}: expected {expected[i]!r}, got {line!r}")
return out, errors
Every operation yields exactly one output string, including failures, so ordering aligns with the expected list. Integer parsing happens in the handlers, and any ValueError becomes a formatted error rather than a crash. When output mismatches, I report the index, the command, and both values—that's what turns a red test into a debuggable one. Adding a WITHDRAW command means adding one handler and one key.
To make sure the harness is itself trustworthy, I'd run the sample test, hand-compute the expected output, and also feed a deliberately failing test to confirm the mismatch report fires.
What I'd watch for
- Using floats for money—never.
- Mutating before validating, leaving partial state on insufficient funds.
- Recomputing activity by scanning a log on every query.
- Non-deterministic tie order, which makes golden-output tests flaky.
- Forgetting that
n > Ais legal input. - Hardcoding command names/formatting without confirming them with the interviewer.