Bank Ledger with Holds, Expiring Transfers and Customer Merge
Data Structure DesignModel answerLast updated
Build an in-memory bank that supports deposits, payments, two-step transfers with expiring holds, a top-activity ranking, and customer merges that leave history untouched.
Design and implement an in-memory, single-threaded BankSystem. Every call carries an integer timestamp. Timestamps never decrease, and amounts are non-negative integers. Explain your data model, the cost of each operation, and how you would test it.
Operations
createAccount(ts, customerId) -> booldeposit(ts, accountId, amount) -> intpay(ts, sourceId, targetId, amount) -> inttransfer(ts, sourceId, targetId, amount) -> str: reserves the money on the source right away and returns a unique transfer id.accept(ts, accountId, transferId) -> bool: the target account confirms the transfer.mergeCustomers(oldId, newId) -> NonetopActivity(ts, n) -> list[str]: ids of thenmost active accounts.
The original wording omitted the source from transfer. Assume the signature above includes it.
Rules
- Accounts. For the first three operations, assume one account per customer, so
accountId == customerId. - Holds.
transfersubtracts the amount from the source immediately. The money sits in the transfer record and cannot be spent elsewhere.acceptcredits the target. - Expiry. A transfer is valid for a fixed window
EXPIRY. A transfer created att0can be accepted whilets < t0 + EXPIRY. Atts >= t0 + EXPIRYit is expired, and the held amount must go back to the source. - Expiry must be visible. Any call that changes or reports a balance (
deposit,pay, and so on) must first unwind all expired transfers, so returned balances are always correct. - Activity. An account's activity is the sum of its deposits, its outgoing payments, and the amounts of accepted transfers (counted for both source and target). Expired transfers add nothing.
topActivitysorts by activity descending, then by id ascending. - Merge.
mergeCustomers(oldId, newId)moves every account owned byoldIdtonewId. Balances, transfers (open, held or settled) and history must be preserved and not rewritten.
Return values you must define
Specify exact results for these cases:
- Missing accounts.
- Insufficient funds.
source == target.- Unknown, expired, duplicate or wrong-account
acceptcalls. - Invalid merges.
Failed calls must not change any state. Explain how a repeated accept stays safe.
Hints
Hint 1
Give every transfer a small state machine (PENDING, ACCEPTED, EXPIRED). Make `accept` succeed only from PENDING, and that status check also gives you idempotency.
Hint 2
Put `(createdAt + EXPIRY, transferId)` in a min-heap and run a sweep at the start of every public call. Skip entries that are no longer PENDING instead of deleting them from the middle.
Hint 3
Keep customer identity separate from account identity. Transfers and history refer to account ids, so a merge only changes an ownership pointer and never has to touch past records.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Pin down the contract first
The task is about precise semantics and time-driven state, not scale. I would state these decisions up front:
| Operation | Success | Failure (state unchanged) |
|---|---|---|
createAccount | True | False if the id exists |
deposit | new balance | -1 if the account is missing |
pay | source balance after paying | -1 if either account is missing, src == tgt, or funds are short |
transfer | "transfer<k>" from a global counter | "" for a missing account, src == tgt, or short funds |
accept | True | False for an unknown id, a caller that is not the target, an expired transfer, or one already accepted |
mergeCustomers | moves ownership | no-op if the ids are equal or either customer is missing |
Boundary rule: at exactly t0 + EXPIRY the transfer is already expired. Activity counts deposits, outgoing payments, and accepted transfers (both sides). I would flag the activity definition as an assumption, since it is the easiest place to disagree with an interviewer.
2. Data model
accounts: id -> Account(balance, activity, owner, history[]). History is append-only.transfers: tid -> Transfer(src, tgt, amount, created, status)withstatusinPENDING / ACCEPTED / EXPIRED.expiry_heap: min-heap of(created + EXPIRY, tid).customers: customerId -> set(accountIds).
The key decision is that transfers and history reference account ids, never customer ids. A merge then rewrites only ownership, and old records stay as they were.
3. Lazy expiry
Because time only moves forward, every public method starts with _expire(ts). It pops heap entries with expiresAt <= ts. If the transfer is still PENDING, it marks it EXPIRED, refunds the source, and appends a refund event to the history. Entries for accepted transfers are skipped (lazy deletion), so the heap never needs a delete-from-middle operation.
I prefer a global sweep over checking only the involved accounts. Every caller sees a consistent world, and each transfer is unwound exactly once. accept also sweeps, so a late accept sees EXPIRED and returns False.
4. Implementation
import heapq
EXPIRY = 86_400_000
class Account:
def __init__(self, owner):
self.balance = 0
self.activity = 0
self.owner = owner
self.history = []
class Transfer:
def __init__(self, src, tgt, amount, created):
self.src, self.tgt, self.amount = src, tgt, amount
self.created = created
self.status = "PENDING"
class BankSystem:
def __init__(self):
self.accounts, self.transfers = {}, {}
self.customers = {}
self.heap, self.counter = [], 0
def _expire(self, ts):
while self.heap and self.heap[0][0] <= ts:
_, tid = heapq.heappop(self.heap)
t = self.transfers[tid]
if t.status == "PENDING":
t.status = "EXPIRED"
s = self.accounts[t.src]
s.balance += t.amount
s.history.append((ts, "refund", tid, t.amount))
def createAccount(self, ts, cid):
self._expire(ts)
if cid in self.accounts:
return False
self.accounts[cid] = Account(cid)
self.customers.setdefault(cid, set()).add(cid)
return True
def deposit(self, ts, aid, amount):
self._expire(ts)
a = self.accounts.get(aid)
if a is None:
return -1
a.balance += amount
a.activity += amount
a.history.append((ts, "deposit", None, amount))
return a.balance
def pay(self, ts, src, tgt, amount):
self._expire(ts)
s, t = self.accounts.get(src), self.accounts.get(tgt)
if s is None or t is None or src == tgt or s.balance < amount:
return -1
s.balance -= amount
t.balance += amount
s.activity += amount
s.history.append((ts, "pay_out", tgt, amount))
t.history.append((ts, "pay_in", src, amount))
return s.balance
def transfer(self, ts, src, tgt, amount):
self._expire(ts)
s = self.accounts.get(src)
if s is None or tgt not in self.accounts or src == tgt or s.balance < amount:
return ""
self.counter += 1
tid = f"transfer{self.counter}"
s.balance -= amount # hold
self.transfers[tid] = Transfer(src, tgt, amount, ts)
heapq.heappush(self.heap, (ts + EXPIRY, tid))
s.history.append((ts, "hold", tid, amount))
return tid
def accept(self, ts, aid, tid):
self._expire(ts)
t = self.transfers.get(tid)
if t is None or t.tgt != aid or t.status != "PENDING":
return False
t.status = "ACCEPTED"
src, tgt = self.accounts[t.src], self.accounts[t.tgt]
tgt.balance += t.amount
src.activity += t.amount
tgt.activity += t.amount
tgt.history.append((ts, "accept_in", tid, t.amount))
src.history.append((ts, "settled", tid, t.amount))
return True
def mergeCustomers(self, old, new):
if old == new or old not in self.customers or new not in self.customers:
return
for aid in self.customers.pop(old):
self.accounts[aid].owner = new
self.customers[new].add(aid)
def topActivity(self, ts, n):
self._expire(ts)
best = heapq.nsmallest(
n, self.accounts.items(), key=lambda kv: (-kv[1].activity, kv[0]))
return [k for k, _ in best]
5. Idempotency and failure safety
- The status field is the guard. A second
acceptseesACCEPTEDand returnsFalse, so nothing is credited twice. - Every method validates everything before mutating anything, so failures leave no partial state.
- The hold is subtracted at
transfertime, so the same funds cannot be paid out or held twice.
6. Complexity
Let A be the number of accounts and T the number of transfers.
createAccount,deposit,pay,accept: O(1) plus the amortized sweep.transfer: O(log T) for the heap push.- Sweep: each transfer is pushed and popped once, so O(log T) amortized per transfer.
mergeCustomers: O(k), where k is the number of accounts owned byoldId.topActivity: O(A log n) with a bounded heap. For frequent queries, keep a sorted structure instead.- Space: O(A + T + total history events).
7. Testing
- Reference model. Write a deliberately naive version that scans all transfers on every call and recomputes expiry from scratch. Run both on thousands of random operation sequences with many accounts and compare every return value.
- Invariants after each step. The sum of balances plus pending holds equals total deposits. No balance is negative. Each transfer is in exactly one terminal state. History length never shrinks.
- Boundaries. Accept at
created + EXPIRY - 1(succeeds) and atcreated + EXPIRY(fails). Test a zero amount,src == tgt, a wrong target, and double accept. - Merge. Compare histories and balances before and after. Merge in chains (A into B, then B into C). Check that transfers created before the merge can still be accepted afterward.
Common mistakes
- Refunding only the accounts named in the current call, which leaves stale balances elsewhere.
- Forgetting that
acceptmust also sweep first. - Counting expired transfers toward activity.
- Storing customer ids inside transfers, which makes a merge rewrite history.
- Mutating state before the validation checks finish.