In-Memory Ledger with Timed Transfers and Account Consolidation
Data Structure DesignModel answerLast updated
Design an in-memory financial ledger supporting deposits, transfers, scheduled future payments, top-K spending rankings, and account merges with pending-payment reconciliation.
In-Memory Ledger with Timed Transfers and Account Consolidation
You are building an in-memory financial ledger for a simulation platform. The ledger must support the six operations below. For each one, define a clear method signature, the data structures you would use, the expected time and space complexity, and any consistency or idempotency guarantees.
Operations
1. open_account(account_id)
Register a new account with a zero balance. Reject if the id is already active or was previously retired by a consolidation.
2. deposit(account_id, amount)
Add amount (positive integer, in cents) to the account's balance.
3. transfer(src_id, dst_id, amount)
Move amount from src to dst. Return True on success, False if funds are insufficient. Reject zero or negative amounts, transfers to the same account, and transfers involving unknown or retired accounts.
4. top_spenders(k)
Return the k accounts with the highest cumulative outgoing amounts (sum of all successful debits, including executed scheduled payments), ordered by outgoing total descending. Break ties by account_id ascending. If fewer than k accounts exist, return all of them.
5. schedule_transfer(src_id, dst_id, amount, execute_at_ms)
Queue a payment to run at or after the epoch-millisecond timestamp execute_at_ms. When a payment becomes due, attempt it exactly once. If the source balance is insufficient at that moment, mark the payment skipped — do not retry. A payment scheduled in the past executes immediately during the next operation's catch-up step.
6. consolidate(primary_id, secondary_id)
Merge the secondary account into the primary. The primary survives; the secondary is retired. Combine balances and outgoing totals. Any pending scheduled payments that referenced the secondary account should seamlessly apply to the primary after consolidation — without being rewritten or re-queued. If a pending payment's source and destination resolve to the same account after consolidation, cancel it.
Scheduling contract
Every operation receives a timestamp argument representing the caller's current time. Before executing the operation itself, the ledger must first process all scheduled payments whose execute_at_ms is less than or equal to timestamp, in chronological order (ties broken by scheduling sequence). This "catch-up then act" rule makes execution deterministic regardless of whether a background timer or an inline call triggers it.
What your answer should cover
- The concrete data structures for balances, outgoing totals, the schedule, account aliasing after consolidations, and idempotent request caching.
- How
top_spendersstays consistent as transfers, scheduled payments, and consolidations mutate outgoing totals, and the trade-off between a simpler O(n log k) query approach versus maintaining a sorted structure for O(log n) updates and O(k) queries. - Correctness arguments: money conservation, at-most-once execution of each scheduled payment, and what happens when two payments are due at the same millisecond.
- Complexity table for all six operations plus the catch-up step.
- Edge cases: zero/negative amounts; self-transfer after consolidation; consolidating an account with itself; chained consolidations (c→b then b→a); ties in
top_spenders;klarger than the account count; a payment whoseexecute_at_msis already in the past when scheduled. - A working implementation in Python (or a language of your choice) that demonstrates the core logic.
Hints
Hint 1
For scheduled payments, a min-heap keyed by (execute_at_ms, sequence_number) gives O(log P) insertion and lets you pop due payments in order during each catch-up step. The sequence number breaks ties and preserves scheduling order when two payments share the same timestamp.
Hint 2
You don't need to rewrite every pending payment when two accounts consolidate. Instead, store a lazy alias map from retired ids to their surviving replacement. Resolve source and destination through this map at execution time. Path-compress the chain so that repeated consolidations (c→b→a) stay near-O(1) per lookup.
Hint 3
For top_spenders, start with a plain hash map of outgoing totals and use heapq.nsmallest(k, …) at query time — O(n log k), simple to implement. If the interview pushes on query frequency, describe the upgrade path: maintain a SortedList of (-total_out, account_id), making each update O(log n) and each query O(k). State the trade-off explicitly rather than over-engineering up front.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem layers four independent concerns on top of each other. Solve each one separately, then compose them.
| Concern | Data structure |
|---|---|
| Balances and outgoing totals | dict[account_id] -> int (integer cents) |
| Due-time ordering | Min-heap of (execute_at_ms, seq, payment_id) |
| Account aliasing after consolidation | dict[retired_id -> survivor_id] with path compression |
| Idempotent request caching | dict[request_id -> cached_result] |
Scheduling: catch-up then act
Every public method accepts a timestamp. The first thing it does is advance the internal clock to max(clock, timestamp) and drain the heap of every payment with execute_at_ms <= clock. Payments run in (execute_at_ms, seq) order. Only after that does the method apply its own effect. This single rule makes the system deterministic: a payment due at time t always executes before any operation stamped t or later, whether the trigger is a background timer or an inline call.
Consolidation: lazy aliasing
When consolidate(primary, secondary) runs:
balance[primary] += balance[secondary]total_out[primary] += total_out[secondary]alias[secondary] = primary— the secondary is retired
No pending payments are touched. At execution time, resolve src and dst through _resolve(), which follows the alias chain and applies path compression. If the resolved source and destination are the same account, cancel the payment rather than executing a self-transfer. This keeps consolidation O(1) regardless of how many payments are pending.
Top spenders
Keep outgoing totals in a plain hash map. At query time, use heapq.nsmallest(k, accounts, key=lambda id: (-total_out[id], id)). That is O(n log k) per query and O(1) per update — the right trade-off when updates are far more frequent than queries.
If queries dominate, upgrade to a SortedList of (-total_out, account_id). Every mutation becomes a remove-old plus insert-new at O(log n), and the query becomes O(k). Mention both and let the interviewer's access-pattern question guide the choice.
Correctness
- Money conservation. Every successful move debits one live account and credits another by the same amount. Consolidation transfers
b's balance intoaand removesb, so nothing is lost or created. - At-most-once execution. Each payment has a
statusfield (PENDING,EXECUTED,SKIPPED,CANCELLED). The heap may contain stale entries (already-processed payments); the status check on pop discards them immediately. - No retry on skip. Insufficient funds at execution time →
SKIPPED, never re-queued. - Idempotency. Cache
(request_id -> result). A duplicate call returns the cached result without re-applying any effect. Entries expire after a TTL in production. - Monotonic clock.
now = max(now, timestamp)prevents a late-arriving request from rolling time backward and un-executing history.
Complexity
| Operation | Time | Notes |
|---|---|---|
open_account, deposit, transfer | O(1) + catch-up | |
schedule_transfer | O(log P) + catch-up | P = pending payments |
| Catch-up | O(m log P) | m payments processed; amortized O(log P) each |
consolidate | O(1) amortized | Path compression on alias chain |
top_spenders | O(n log k) | O(k) with SortedList variant |
Space: O(n + P + R) where n = accounts, P = payments ever scheduled, R = cached request ids.
Edge cases
- Zero or negative amounts — rejected at the call boundary for deposit, transfer, and schedule.
- Self-transfer — rejected. Also rejected post-consolidation if the resolved src and dst become the same account.
- Insufficient funds — transfer returns
False; scheduled payment is markedSKIPPED. - Unknown or retired account — rejected. Scheduling also requires both endpoints to be currently active.
- Payment scheduled in the past —
execute_at_ms <= nowat scheduling time, so it runs during the same call's catch-up. - Two payments due at the same millisecond — run in scheduling order (
seq). The first may drain the balance, causing the second to be skipped. - Chained consolidations (c→b, then b→a) —
_resolvefollows the chain; path compression keeps subsequent lookups O(1) amortized. - Consolidating an account with itself or a retired account — rejected.
- k larger than account count — return all active accounts.
- Ties in top_spenders — broken by
account_idascending.
Implementation
import heapq
import threading
from typing import Dict, List, Optional, Tuple
class Ledger:
def __init__(self) -> None:
self.balance: Dict[str, int] = {}
self.total_out: Dict[str, int] = {}
self.alias: Dict[str, str] = {} # retired_id -> survivor_id
self.heap: List[Tuple[int, int, str]] = [] # (execute_at, seq, pid)
self.payments: Dict[str, dict] = {}
self.results: Dict[str, object] = {} # request_id -> cached result
self.seq = 0
self.now = 0
self.lock = threading.Lock()
# ── internals ──────────────────────────────────────────────
def _resolve(self, acc: str) -> str:
"""Follow alias chain with path compression."""
root = acc
while root in self.alias:
root = self.alias[root]
while acc in self.alias:
nxt = self.alias[acc]
self.alias[acc] = root
acc = nxt
return root
def _active(self, acc: str) -> bool:
return acc in self.balance
def _move(self, src: str, dst: str, amount: int) -> None:
self.balance[src] -= amount
self.balance[dst] += amount
self.total_out[src] += amount
def _catch_up(self, ts: int) -> None:
self.now = max(self.now, ts)
while self.heap and self.heap[0][0] <= self.now:
_, _, pid = heapq.heappop(self.heap)
p = self.payments[pid]
if p["status"] != "PENDING":
continue
s = self._resolve(p["src"])
d = self._resolve(p["dst"])
if s == d:
p["status"] = "CANCELLED"
elif self.balance.get(s, 0) < p["amount"]:
p["status"] = "SKIPPED"
else:
self._move(s, d, p["amount"])
p["status"] = "EXECUTED"
# ── public API ─────────────────────────────────────────────
def open_account(self, account_id: str, timestamp: int) -> bool:
with self.lock:
self._catch_up(timestamp)
if account_id in self.balance or account_id in self.alias:
return False
self.balance[account_id] = 0
self.total_out[account_id] = 0
return True
def deposit(self, account_id: str, amount: int, timestamp: int) -> bool:
with self.lock:
self._catch_up(timestamp)
if amount <= 0 or not self._active(account_id):
return False
self.balance[account_id] += amount
return True
def transfer(
self,
src_id: str,
dst_id: str,
amount: int,
timestamp: int,
request_id: Optional[str] = None,
) -> bool:
with self.lock:
if request_id and request_id in self.results:
return self.results[request_id]
self._catch_up(timestamp)
ok = (
amount > 0
and src_id != dst_id
and self._active(src_id)
and self._active(dst_id)
and self.balance[src_id] >= amount
)
if ok:
self._move(src_id, dst_id, amount)
if request_id:
self.results[request_id] = ok
return ok
def schedule_transfer(
self,
src_id: str,
dst_id: str,
amount: int,
execute_at_ms: int,
timestamp: int,
) -> Optional[str]:
with self.lock:
self._catch_up(timestamp)
if amount <= 0 or not self._active(src_id) or not self._active(dst_id):
return None
self.seq += 1
pid = f"pay-{self.seq}"
self.payments[pid] = {
"src": src_id,
"dst": dst_id,
"amount": amount,
"status": "PENDING",
}
heapq.heappush(self.heap, (execute_at_ms, self.seq, pid))
# If due immediately, catch_up at execute_at_ms will handle it
# on the next operation; force it now if already past due.
if execute_at_ms <= self.now:
self._catch_up(self.now)
return pid
def top_spenders(self, k: int, timestamp: int) -> List[str]:
with self.lock:
self._catch_up(timestamp)
return [
acc
for _, acc in heapq.nsmallest(
k,
self.total_out.items(),
key=lambda item: (-item[1], item[0]),
)
]
def consolidate(
self, primary_id: str, secondary_id: str, timestamp: int
) -> bool:
with self.lock:
self._catch_up(timestamp)
if (
primary_id == secondary_id
or not self._active(primary_id)
or not self._active(secondary_id)
):
return False
self.balance[primary_id] += self.balance.pop(secondary_id)
self.total_out[primary_id] += self.total_out.pop(secondary_id)
self.alias[secondary_id] = primary_id
return True
Common mistakes
- Rewriting pending payments on merge. O(P) work per consolidation and easy to miss edge cases. Lazy aliasing is strictly better.
- Float amounts. Use integer cents. Floating-point rounding causes balances to drift.
- Not processing catch-up before the operation's own effect. A transfer stamped
t=100must see the balance after all payments due att <= 100have run. - Forgetting self-transfer after consolidation. A payment from account
bto accounta, scheduled beforeconsolidate(a, b), must be cancelled, not executed. - Skipping status check on heap pop. Stale entries for already-executed or cancelled payments will always be in the heap; check status immediately after popping.