Building a Multi-Level Credit Ledger with Timed Transfers and Merges
Data Structure DesignModel answerLast updated
Build an in-memory ledger of credit-holding workspaces in four stages: transfers with a top-k ranking, timed transfers with cancellation, workspace merges, and point-in-time balance lookups.
Implement a class WorkspaceManager that tracks workspaces holding credit, like bank accounts that can pay one another. The work comes in four levels. Each level adds methods, and everything from earlier levels must keep working. Exact return values matter, so treat them as a spec that automated tests would check.
Ground rules
- Every method takes an integer
timestampas its first argument. Timestamps strictly increase from call to call. - Workspace ids are non-empty strings. Every
amountanddelayis a positive integer. - Balances are integers and never drop below zero.
- Invalid requests (such as an unknown id) return the failure value listed for the method. They never raise.
Policies fixed for this version
- Failures return a sentinel (
FalseorNone) rather than raising. top_kbreaks ties by workspace id, ascending.- A scheduled transfer checks the sender's balance only when it executes. Nothing is set aside when it is scheduled.
- After a workspace is merged away, its id may be created again as a new workspace with its own history.
- After a merge, the target's history shows the absorbed credit only from the merge time onward.
Level 1: Creating workspaces and adding credit
create_workspace(timestamp, workspace_id) -> bool: create a workspace with 0 credit. ReturnFalseand change nothing if the id exists.add_credit(timestamp, workspace_id, amount) -> int | None: add credit and return the new balance, orNoneif the workspace does not exist.
Level 2: Immediate transfers and ranking
transfer(timestamp, source_id, target_id, amount) -> int | None: move credit now and return the source's new balance. ReturnNoneand change nothing if either workspace is missing, the two ids are equal, or the source holds less thanamount.top_k(timestamp, k) -> list[tuple[str, int]]: return(workspace_id, balance)for thekworkspaces with the most credit, highest first, ties by id ascending. If fewer thankworkspaces exist, return all of them.
Level 3: Scheduled transfers
schedule_transfer(timestamp, source_id, target_id, amount, delay) -> str | None: register a transfer due attimestamp + delay. Return ids"transfer1","transfer2", ... in creation order. ReturnNoneif either workspace is missing or the ids are equal.cancel_transfer(timestamp, transfer_id) -> bool: cancel a transfer that is still pending and returnTrue. ReturnFalseif the id is unknown or the transfer has already executed, failed or been canceled.
Rules:
- Before any call at time
tdoes its own work, every pending transfer due at or beforetexecutes, ordered by due time and then by creation order. A cancel arriving at or after the due time is too late. - If the sender cannot cover the amount at execution time, the transfer fails and changes nothing.
Level 4: Merging and historical balances
merge_workspaces(timestamp, target_id, source_id) -> bool: the target receives all of the source's credit, the source is deleted, and every still-pending scheduled transfer involving the source (as sender or receiver) is canceled. ReturnFalseand change nothing if either workspace is missing or the ids are equal. Transfers due at or beforetimestamprun first, so only those still pending afterward are canceled.get_balance(timestamp, workspace_id, time_at) -> int | None, withtime_at <= timestamp: return the balance attime_at, after all changes made at times up to and includingtime_at. ReturnNoneif no workspace with that id existed attime_at. An executed scheduled transfer counts as happening at its due time. A merged-away workspace stops existing at the merge time, but its earlier history can still be queried.
Example
| Call | Returns | Note |
|---|---|---|
create_workspace(1, "A") | True | |
create_workspace(2, "B") | True | |
add_credit(3, "A", 100) | 100 | |
transfer(4, "A", "B", 30) | 70 | A=70, B=30 |
schedule_transfer(5, "B", "A", 20, 5) | "transfer1" | due at 10 |
top_k(6, 2) | [("A", 70), ("B", 30)] | |
get_balance(11, "A", 9) | 70 | transfer1 runs first, at time 10 |
get_balance(12, "A", 10) | 90 | |
merge_workspaces(13, "A", "B") | True | A = 90 + 10 |
get_balance(14, "B", 12) | 10 | |
get_balance(15, "B", 13) | None | B merged away at 13 |
top_k(16, 5) | [("A", 100)] |
What to deliver
Explain your design and the data structures behind each level, state the complexity of each operation, give working code, and point out the edge cases you handle.
Hints
Hint 1
Give every public method the same first step: run all pending transfers due at or before the call's timestamp. That one rule makes 'cancel too late' and 'merge only cancels what is still pending' follow naturally.
Hint 2
Keep pending transfers in a min-heap keyed by (due_time, creation_sequence). Cancel by marking the record, and let the catch-up loop skip anything that is no longer pending.
Hint 3
For history, store sorted (time, balance) change points per workspace and binary search them. Keep one record per incarnation of an id, with created and deleted times, so a re-created id never mixes with the old one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Design
Two classes keep each level an extension rather than a rewrite. Account holds one incarnation of a workspace. WorkspaceManager owns lookup, the pending-transfer heap and the id counter.
Account: id, created, deleted (None while alive), parallel lists times and vals of balance change points (the current balance is vals[-1]), and a set of pending transfer ids that involve it.
Manager:
live: id to the currentAccount.incarnations: id to everyAccountever created under that id, ordered bycreated.heap: min-heap of(due, seq, transfer_id).transfers: id to a record with statuspending | executed | failed | canceled.
Key decisions
- Catch-up first, in every public method.
_catch_up(t)pops heap entries withdue <= tand executes them. Heap order(due, seq)gives the required determinism: earlier due time first, creation order on ties. Because it runs before the method's own logic, a cancel at or after the due time returnsFalse, and a merge cancels only transfers that are truly still pending. - Lazy cancellation. Deleting from the middle of a heap is awkward, so mark the record
canceledand skip it when popped. Each transfer costs O(log n) in total. - Executed transfers are recorded at their due time. This keeps history append-only. Any earlier call would have executed the transfer had its timestamp reached the due time, so every account's change points arrive in nondecreasing time. If two changes land on the same time, overwrite the last point so the entry shows the final balance at that time.
- History lookup. Find the incarnation with the latest
created <= time_at, then checkdeleted is None or time_at < deleted. Next, binary search itstimesfor the last change point at or beforetime_at. Cost is O(log n). - Merge order. Catch up, validate, cancel the source's pending transfers (using its own pending set, so no global scan), add the source's balance to the target at
timestamp, setsource.deleted = timestamp, and remove it fromlive. Settingdeletedto the merge time makesget_balancereturnNoneat exactly that time, as in the example. The target only gains a new change point, so its earlier balances are untouched. - Top-k.
heapq.nsmallest(k, accounts, key=(-balance, id))costs O(n log k). If rankings are read far more often than balances change, mention a sorted container keyed by(-balance, id), updated on each mutation, for O(log n) updates and O(k) reads.
Code
import bisect
import heapq
class Account:
def __init__(self, wid, t):
self.id, self.created, self.deleted = wid, t, None
self.times, self.vals = [t], [0]
self.pending = set()
@property
def balance(self):
return self.vals[-1]
def set(self, t, v):
if self.times[-1] == t:
self.vals[-1] = v
else:
self.times.append(t)
self.vals.append(v)
def at(self, t):
i = bisect.bisect_right(self.times, t) - 1
return self.vals[i] if i >= 0 else None
class WorkspaceManager:
def __init__(self):
self.live, self.incarnations = {}, {}
self.heap, self.transfers, self.count = [], {}, 0
def _catch_up(self, t):
while self.heap and self.heap[0][0] <= t:
due, _, tid = heapq.heappop(self.heap)
tr = self.transfers[tid]
if tr["status"] != "pending":
continue
src, dst = self.live[tr["src"]], self.live[tr["dst"]]
src.pending.discard(tid)
dst.pending.discard(tid)
if src.balance >= tr["amount"]:
src.set(due, src.balance - tr["amount"])
dst.set(due, dst.balance + tr["amount"])
tr["status"] = "executed"
else:
tr["status"] = "failed"
def create_workspace(self, t, wid):
self._catch_up(t)
if wid in self.live:
return False
acc = Account(wid, t)
self.live[wid] = acc
self.incarnations.setdefault(wid, []).append(acc)
return True
def add_credit(self, t, wid, amount):
self._catch_up(t)
acc = self.live.get(wid)
if acc is None:
return None
acc.set(t, acc.balance + amount)
return acc.balance
def transfer(self, t, src_id, dst_id, amount):
self._catch_up(t)
src, dst = self.live.get(src_id), self.live.get(dst_id)
if src is None or dst is None or src is dst or src.balance < amount:
return None
src.set(t, src.balance - amount)
dst.set(t, dst.balance + amount)
return src.balance
def top_k(self, t, k):
self._catch_up(t)
best = heapq.nsmallest(k, self.live.values(),
key=lambda a: (-a.balance, a.id))
return [(a.id, a.balance) for a in best]
def schedule_transfer(self, t, src_id, dst_id, amount, delay):
self._catch_up(t)
src, dst = self.live.get(src_id), self.live.get(dst_id)
if src is None or dst is None or src is dst:
return None
self.count += 1
tid = f"transfer{self.count}"
self.transfers[tid] = {"src": src_id, "dst": dst_id,
"amount": amount, "status": "pending"}
heapq.heappush(self.heap, (t + delay, self.count, tid))
src.pending.add(tid)
dst.pending.add(tid)
return tid
def cancel_transfer(self, t, tid):
self._catch_up(t)
tr = self.transfers.get(tid)
if tr is None or tr["status"] != "pending":
return False
tr["status"] = "canceled"
self.live[tr["src"]].pending.discard(tid)
self.live[tr["dst"]].pending.discard(tid)
return True
def merge_workspaces(self, t, target_id, source_id):
self._catch_up(t)
tgt, src = self.live.get(target_id), self.live.get(source_id)
if tgt is None or src is None or tgt is src:
return False
for tid in list(src.pending):
tr = self.transfers[tid]
tr["status"] = "canceled"
self.live[tr["src"]].pending.discard(tid)
self.live[tr["dst"]].pending.discard(tid)
tgt.set(t, tgt.balance + src.balance)
src.deleted = t
del self.live[source_id]
return True
def get_balance(self, t, wid, time_at):
self._catch_up(t)
accs = self.incarnations.get(wid, [])
i = bisect.bisect_right(accs, time_at, key=lambda a: a.created) - 1
if i < 0:
return None
acc = accs[i]
if acc.deleted is not None and time_at >= acc.deleted:
return None
return acc.at(time_at)
bisect with key= needs Python 3.10+. Otherwise keep a parallel list of created times.
Complexity
create_workspace,add_credit,transfer,cancel_transfer: O(1) plus amortized catch-up.schedule_transfer: O(log n).top_k: O(n log k).merge_workspaces: O(p), where p is the source's pending transfer count.get_balance: O(log n).- Catch-up costs O(log n) per executed or discarded transfer.
Edge cases and common mistakes
- Forgetting catch-up in some method.
get_balance,top_kandcancel_transferall need it. - Self-transfer or self-merge. Reject both before changing any state.
- Validation order. Check everything first and mutate after, so failures change nothing.
- Insufficient credit at execution time. The transfer fails permanently and is not retried.
- Merging with pending transfers. Cancel them before the source disappears, or catch-up will look up a missing account.
- Re-created ids. Without per-incarnation records, an old history leaks into the new workspace.
- Same-time changes. A transfer due at
tand a call attshould yield one final balance fort, which is whysetoverwrites.