In-Memory Transaction Ledger with Aliases and History
Data Structure DesignModel answerLast updated
Implement a timestamped in-memory ledger supporting deposits, cashback transfers, scheduled execution, account merging with alias resolution, and point-in-time balance queries.
In-Memory Transaction Ledger
You are building a simplified in-memory financial ledger. Implement a class MoneyLedger that tracks account balances over time. All method calls arrive with non-decreasing timestamps.
Methods
open_account(account_id: str) -> bool
Opens a new account with a starting balance of 0. Returns False if account_id already exists or is a known alias of another account. Returns True on success. This method takes no timestamp.
deposit(timestamp: int, account_id: str, amount: int) -> int | None
Adds amount to the account. Returns the new balance, or None if the account does not exist or amount <= 0.
transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> bool
Moves amount from source_id to target_id. On success:
- Deducts
amountfrom the sender. - Credits
amountto the receiver. - Immediately credits a cashback of
(amount * 2) // 100back to the sender (integer floor division). - Returns
True.
Returns False if either account does not exist, amount <= 0, the two IDs resolve to the same account (including through aliases), or the sender's balance is less than amount.
queue_transfer(timestamp: int, job_id: str, source_id: str, target_id: str, amount: int, run_at: int) -> bool
Schedules a transfer to execute at time run_at, where run_at > timestamp. Returns False if job_id has already been used (even for a completed job). Does not check or reserve funds at scheduling time. Returns True if the job is queued successfully.
merge_accounts(timestamp: int, primary_id: str, secondary_id: str) -> bool
Absorbs secondary_id into primary_id. All funds in secondary_id move to primary_id. From this point on, any operation that references secondary_id automatically targets primary_id instead. Returns False if either account does not exist or both IDs already resolve to the same account. Returns True on success.
balance_at(timestamp: int, account_id: str, when: int | None = None) -> int | None
Returns the balance for account_id. If when is None, returns the current balance as of timestamp. If when is provided, returns the balance immediately after all transactions at or before when were applied. Returns None if account_id does not exist.
top_senders(timestamp: int, k: int) -> list[str]
Returns the k account IDs with the highest total gross outgoing transfer amounts. Gross outgoing means the full amount sent, before cashback. Ties are broken by lexicographic order of the canonical account ID (ascending).
Scheduling Rules
Before processing any timestamped method at time T, the ledger must first execute all queued transfers whose run_at <= T, in ascending order of run_at. When two jobs share the same run_at, execute them in lexicographic order of job_id. A job that fails at execution time (insufficient funds, missing account, same-account resolution) is discarded silently and never retried.
Example
ledger = MoneyLedger()
ledger.open_account("alice") # True
ledger.open_account("bob") # True
ledger.deposit(1, "alice", 1000) # 1000
ledger.queue_transfer(2, "j1", "alice", "bob", 500, 10) # True
ledger.transfer(5, "alice", "bob", 200)
# alice: 1000 - 200 + 4 cashback = 804. bob: 200.
# Returns True
ledger.balance_at(10, "alice")
# Before answering, j1 runs: alice sends 500, gets 10 cashback.
# alice: 804 - 500 + 10 = 314. bob: 700.
# Returns 314
ledger.top_senders(10, 1) # ["alice"] (gross sent: 200 + 500 = 700)
ledger.merge_accounts(12, "bob", "alice")
# True. bob now has 700 + 314 = 1014. "alice" is an alias for "bob".
ledger.deposit(15, "alice", 100) # 1114 (alias resolves to bob)
ledger.balance_at(15, "bob") # 1114
ledger.balance_at(15, "alice", when=1) # 1000 (alice's historical balance at t=1)
Constraints
1 <= timestamp, non-decreasing across calls.1 <= amount <= 10^9for all financial operations.1 <= k <= number of accounts.run_at > timestampat scheduling time.- Account IDs and job IDs consist of lowercase letters and digits.
- Up to 5 × 10^4 total method calls.
Hints
Hint 1
Before implementing anything else, think about how to drain the scheduled-job queue. Every timestamped method must do this first. A min-heap keyed on (run_at, job_id) gives you the right execution order with no extra sorting.
Hint 2
Account merging needs two separate structures: a union-find (with path compression) for fast current-time resolution, and a separate append-only map from each merged ID to (merge_timestamp, canonical_target). Path compression destroys the merge history, which is why you can't rely on it alone for historical queries.
Hint 3
For point-in-time balance lookups, store per-account parallel lists of (timestamp, balance_after_change). A bisect_right search finds the right snapshot in O(log H). For historical queries on a merged account, walk the merge-history chain stopping at the first merge whose timestamp is strictly after `when`.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem layers five concerns on top of each other. The cleanest path is to solve each concern independently, then wire them together.
The five concerns
1. Scheduled execution (lazy drain)
Keep a min-heap of (run_at, job_id, src, tgt, amount). Python compares tuples left-to-right, so this heap naturally gives the required order: earliest run_at first, then lexicographic job_id for ties. Every timestamped public method starts by popping everything with run_at <= timestamp and running each job through the same internal transfer routine. This is the "lazy" or "drain-on-access" pattern.
2. Alias resolution (union-find)
merge_accounts calls for a union-find. Path compression keeps find() at O(α). All business logic — balance reads, transfer execution, top-spender tracking — calls find() before touching any data, so aliases are transparent everywhere.
3. Merge history (separate log)
Path compression rewrites the parent pointers, which would corrupt historical queries. So store a separate merged_into dict: secondary_canonical_id → (merge_timestamp, primary_canonical_id). This is append-only and never mutated. For a historical query at time when, walk this chain and stop as soon as a merge happened after when.
4. Balance history (sorted lists + binary search)
Each canonical account has two parallel lists: hist_t (timestamps) and hist_b (balance snapshots). Any operation that changes a balance appends (current_timestamp, new_balance). Because the drain step ensures we never go back in time, these lists are always sorted. bisect_right(hist_t, when) - 1 gives the last entry at or before when in O(log H).
5. Spend counters
Each canonical account accumulates a gross outgoing total. A merge adds the absorbed account's total to the surviving account. top_senders runs heapq.nlargest over the spend map.
Common mistakes
- Not draining before every operation. A scheduled transfer might change balances that the current operation depends on. Always drain first.
- Checking funds at schedule time. The spec says funds are checked at execution time only. Reserving them early is wrong.
- Using path compression for historical lookups. After
alice → bob → carol, the compressed path foralicepoints straight tocarol, hiding the intermediate merge atbob. Themerged_intolog avoids this. - Cashback included in gross spend. Cashback is a credit, not a deduction from the gross. The spend counter tracks only the
amountsent. - Duplicate
job_idafter completion. Job IDs must be rejected for reuse even after the job has already run. Track all seen IDs in a set.
Complexity
| Operation | Time |
|---|---|
deposit, transfer, merge_accounts | O(α(n)) + drain cost |
queue_transfer | O(log S), S = pending jobs |
| Each drained job | O(log S · α(n)) |
balance_at (current) | O(α(n)) |
balance_at (historical) | O(m + log H), m = merge-chain length |
top_senders | O(A log k), A = total accounts |
Space: O(A + S + total balance changes).
Python Implementation
import heapq
from bisect import bisect_right
class MoneyLedger:
def __init__(self):
# union-find: id -> parent id (path-compressed for current lookups)
self.parent: dict[str, str] = {}
# merge history: secondary canonical -> (merge_ts, primary canonical)
self.merged_into: dict[str, tuple[int, str]] = {}
# per canonical account
self.balance: dict[str, int] = {}
self.gross_sent: dict[str, int] = {}
self.hist_t: dict[str, list[int]] = {} # timestamps of balance changes
self.hist_b: dict[str, list[int]] = {} # balance after each change
# scheduling
self.heap: list[tuple] = [] # (run_at, job_id, src, tgt, amount)
self.seen_jobs: set[str] = set()
# ---- union-find ----
def _find(self, a: str) -> str:
root = a
while self.parent[root] != root:
root = self.parent[root]
# path compression
while self.parent[a] != root:
self.parent[a], a = root, self.parent[a]
return root
# ---- history helpers ----
def _snapshot(self, acc: str, ts: int) -> None:
"""Append current balance to history for canonical account `acc`."""
self.hist_t[acc].append(ts)
self.hist_b[acc].append(self.balance[acc])
def _lookup_history(self, acc: str, when: int) -> int:
"""Balance of canonical account `acc` at or before `when`."""
idx = bisect_right(self.hist_t[acc], when) - 1
return self.hist_b[acc][idx] if idx >= 0 else 0
# ---- scheduled job drain ----
def _drain(self, ts: int) -> None:
while self.heap and self.heap[0][0] <= ts:
run_at, job_id, src, tgt, amount = heapq.heappop(self.heap)
self._execute_transfer(run_at, src, tgt, amount)
# ---- core transfer logic ----
def _execute_transfer(self, ts: int, src: str, tgt: str, amount: int) -> bool:
if amount <= 0:
return False
if src not in self.parent or tgt not in self.parent:
return False
s, t = self._find(src), self._find(tgt)
if s == t:
return False
if self.balance[s] < amount:
return False
cashback = (amount * 2) // 100
self.balance[s] += cashback - amount
self.balance[t] += amount
self.gross_sent[s] += amount
self._snapshot(s, ts)
self._snapshot(t, ts)
return True
# ---- public API ----
def open_account(self, account_id: str) -> bool:
if account_id in self.parent:
return False
self.parent[account_id] = account_id
self.balance[account_id] = 0
self.gross_sent[account_id] = 0
self.hist_t[account_id] = []
self.hist_b[account_id] = []
return True
def deposit(self, timestamp: int, account_id: str, amount: int) -> int | None:
self._drain(timestamp)
if account_id not in self.parent or amount <= 0:
return None
acc = self._find(account_id)
self.balance[acc] += amount
self._snapshot(acc, timestamp)
return self.balance[acc]
def transfer(self, timestamp: int, source_id: str,
target_id: str, amount: int) -> bool:
self._drain(timestamp)
return self._execute_transfer(timestamp, source_id, target_id, amount)
def queue_transfer(self, timestamp: int, job_id: str, source_id: str,
target_id: str, amount: int, run_at: int) -> bool:
self._drain(timestamp)
if job_id in self.seen_jobs or run_at <= timestamp:
return False
self.seen_jobs.add(job_id)
heapq.heappush(self.heap, (run_at, job_id, source_id, target_id, amount))
return True
def merge_accounts(self, timestamp: int,
primary_id: str, secondary_id: str) -> bool:
self._drain(timestamp)
if primary_id not in self.parent or secondary_id not in self.parent:
return False
p, s = self._find(primary_id), self._find(secondary_id)
if p == s:
return False
# move funds
self.balance[p] += self.balance[s]
self.gross_sent[p] += self.gross_sent[s]
self._snapshot(p, timestamp)
# record merge history before compressing
self.merged_into[s] = (timestamp, p)
# union: secondary canonical points to primary canonical
self.parent[s] = p
return True
def balance_at(self, timestamp: int, account_id: str,
when: int | None = None) -> int | None:
self._drain(timestamp)
if account_id not in self.parent:
return None
if when is None:
return self.balance[self._find(account_id)]
# historical: walk merge chain up to `when`
# start with the canonical id at open time (account_id itself if never merged early)
acc = account_id
# account_id might itself be an alias introduced only at open_account time;
# find its canonical at creation: it's just account_id (no compression needed here
# because we walk merged_into manually)
# resolve current canonical just to confirm the account exists
_ = self._find(account_id)
# walk merge history
canonical = account_id
while canonical in self.merged_into:
merge_ts, next_canonical = self.merged_into[canonical]
if merge_ts <= when:
canonical = next_canonical
else:
break
return self._lookup_history(canonical, when)
def top_senders(self, timestamp: int, k: int) -> list[str]:
self._drain(timestamp)
# only canonical accounts (parent[x] == x) are real accounts
candidates = [
(-spent, acc_id)
for acc_id, spent in self.gross_sent.items()
if self.parent.get(acc_id) == acc_id
]
# sort by descending spend, then ascending id for ties
candidates.sort(key=lambda x: (x[0], x[1]))
return [acc_id for _, acc_id in candidates[:k]]
The balance_at historical walk starts from account_id (not its compressed parent), follows merged_into links only when the merge occurred at or before when, and stops when no further merge applies. This correctly handles chains of arbitrary depth.