Stateful Credit Ledger with Delayed Transfers and Account Merges
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Implement WorkspaceManager, an in-memory credit ledger that tracks organizational accounts ("workspaces") across monotonically advancing integer timestamps. Invalid operations never raise exceptions; instead, they leave ledger state unchanged and return the method's failure sentinel (False or None).
Lazy Scheduled-Execution Rule
Every public method receives timestamp: int as its first argument, and timestamps strictly increase from one call to the next. Nothing runs asynchronously in the background: before any method call at timestamp performs its own validation or state update (even for read-only or failing calls), all still-pending scheduled transfers with due_time <= timestamp must be processed first:
- Due transfers run in ascending order of
due_time, breaking ties by creation order ("transfer1"before"transfer2","transfer2"before"transfer10", and so on). - Funds are checked only at execution time (never reserved when scheduled). If the sender's balance at execution time is strictly less than
amount, that scheduled transfer transitions to failed and changes neither balance. - Otherwise,
amountmoves from sender to receiver, and both balance changes are recorded atdue_time(not the outer caller'stimestamp).
Operations
-
Account Creation & Deposits:
create_workspace(timestamp: int, workspace_id: str) -> bool: creates an active workspace with initial balance0and returnsTrue, or returnsFalseifworkspace_idis already active. (An identifier retired by an earlier merge may be created again later as a brand-new account with independent history.)add_credit(timestamp: int, workspace_id: str, amount: int) -> Optional[int]: addsamounttoworkspace_idand returns its updated balance, or returnsNoneifworkspace_idis not currently active.
-
Immediate Transfers & Leaderboard:
transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: atomically movesamountfromsource_idtotarget_idattimestampand returnssource_id's resulting balance. ReturnsNonewithout modifying any state if either workspace is not active,source_id == target_id, orsource_id's balance is less thanamount.top_k(timestamp: int, k: int) -> List[Tuple[str, int]]: returns up tok(workspace_id, balance)pairs among currently active workspaces, sorted bybalancedescending and breaking ties byworkspace_idascending. Returns all active workspaces if fewer thankexist, or[]ifk <= 0.
-
Delayed Transfers & Cancellation:
schedule_transfer(timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: registers a pending transfer withdue_time = timestamp + delayand returns sequential identifiers"transfer1","transfer2","transfer3", ... across accepted calls. ReturnsNone(without consuming a sequence number) if either workspace is not active orsource_id == target_id.cancel_transfer(timestamp: int, transfer_id: str) -> bool: cancelstransfer_idand returnsTrueif it exists and remains pending after processing transfers due at or beforetimestamp. ReturnsFalseiftransfer_idis unknown or has already executed, failed, or been canceled (so canceling attimestamp >= due_timealways returnsFalse).
-
Account Consolidation & Historical Point-in-Time Queries:
merge_workspaces(timestamp: int, target_id: str, source_id: str) -> bool: if both workspaces are active andtarget_id != source_id, cancels every still-pending scheduled transfer touchingsource_id(whether as sender or receiver), addssource_id's entire current balance totarget_idattimestamp(without copyingsource_id's prior history intotarget_id), retiressource_idstarting attimestamp, and returnsTrue; otherwise returnsFalse.get_balance(timestamp: int, workspace_id: str, time_at: int) -> Optional[int]: returns the balance ofworkspace_idafter all updates with effective time<= time_at, orNoneiftime_at > timestampor no workspace withworkspace_idwas active attime_at. A workspace created att_startand merged away att_mergeis active on the half-open interval[t_start, t_merge), so its pre-merge balances remain queryable fort_start <= time_at < t_merge, whiletime_at == t_mergereturnsNone.
Examples
Example 1
| Call | Return Value | State Notes |
|---|---|---|
create_workspace(2, "eng") |
True |
"eng" opens at t = 2 with 0 |
create_workspace(4, "ops") |
True |
"ops" opens at t = 4 with 0 |
add_credit(5, "eng", 250) |
250 |
"eng" = 250 |
transfer(8, "eng", "ops", 90) |
160 |
"eng" = 160, "ops" = 90 |
schedule_transfer(10, "ops", "eng", 40, 6) |
"transfer1" |
Queued for due_time = 16 |
top_k(12, 2) |
[("eng", 160), ("ops", 90)] |
12 < 16, so "transfer1" has not run yet |
get_balance(18, "eng", 15) |
160 |
"transfer1" executes at effective time 16; at 15, "eng" still had 160 |
get_balance(19, "eng", 16) |
200 |
At 16, "eng" received +40 (160 + 40 = 200) and "ops" became 50 |
merge_workspaces(20, "eng", "ops") |
True |
"eng" becomes 200 + 50 = 250; "ops" is retired at 20 |
get_balance(21, "ops", 19) |
50 |
Pre-merge history of "ops" at t = 19 |
get_balance(22, "ops", 20) |
None |
"ops" stopped existing at t = 20 |
top_k(25, 3) |
[("eng", 250)] |
Only "eng" remains active |
Walk-through: When get_balance(18, "eng", 15) arrives, "transfer1" (due_time = 16 <= 18) executes first and stamps its +40 / -40 updates at 16, leaving "eng"'s balance at 15 untouched (160) and updating "eng" at 16 to 200. Merging "ops" into "eng" at 20 moves "ops"'s remaining 50 credits into "eng" and closes "ops"'s active interval [4, 20).
Example 2
| Call | Return Value | State Notes |
|---|---|---|
create_workspace(1, "core") |
True |
|
create_workspace(2, "ads") |
True |
|
create_workspace(3, "ml") |
True |
|
add_credit(4, "core", 80) |
80 |
|
add_credit(5, "ml", 80) |
80 |
|
top_k(6, 2) |
[("core", 80), ("ml", 80)] |
Tied at 80; "core" < "ml" |
schedule_transfer(7, "core", "ads", 50, 5) |
"transfer1" |
Due at 12 (created first) |
schedule_transfer(8, "core", "ml", 50, 4) |
"transfer2" |
Also due at 12 (created second) |
schedule_transfer(9, "ml", "ads", 25, 10) |
"transfer3" |
Due at 19 |
cancel_transfer(11, "transfer3") |
True |
Canceled before 19 |
cancel_transfer(12, "transfer1") |
False |
At 12, "transfer1" runs first (core -> 30, ads -> 50) and "transfer2" fails (30 < 50) |
merge_workspaces(15, "core", "ads") |
True |
"core" becomes 30 + 50 = 80; "ads" retired at 15 |
create_workspace(17, "ads") |
True |
"ads" recreated at 17 with balance 0 |
get_balance(18, "ads", 14) |
50 |
First lifetime [2, 15) |
get_balance(19, "ads", 16) |
None |
Inactive gap [15, 17) |
get_balance(20, "ads", 18) |
0 |
Second lifetime [17, ...) |
Walk-through: Both "transfer1" and "transfer2" fall due at 12. Creation order runs "transfer1" first, leaving "core" with 30 so "transfer2" fails without debiting "core". Consequently, cancel_transfer(12, "transfer1") arrives too late and returns False. Recreating "ads" at 17 starts a separate lifetime while preserving [2, 15) and the None gap at 16.
Constraints
timestamp >= 1, strictly increasing across consecutive method calls.workspace_id,source_id, andtarget_idare non-empty strings.amount >= 1anddelay >= 1are positive integers;kandtime_atare integers withtime_at <= timestampon valid historical queries.- Account balances are always non-negative integers.
Step-by-step walkthrough
Understand the four-stage contract and the lazy clock
In progressive stateful-design problems, the biggest trap is modeling early methods in a way that forces a complete rewrite when delayed actions and historical queries arrive. Before writing code, list all eight methods, their failure sentinels, and the single timing rule that governs every one of them:
Method Success return Failure return create_workspace(t, id)TrueFalseifidis currently activeadd_credit(t, id, amount)new integer balance Noneifidis not activetransfer(t, src, dst, amount)src's new balanceNone(no balance changes)top_k(t, k)[(id, balance), ...][]ifk <= 0or no workspaces existschedule_transfer(t, src, dst, amount, delay)"transfer1","transfer2", ...None(does not consume an ID number)cancel_transfer(t, transfer_id)TrueFalsemerge_workspaces(t, dst, src)TrueFalseget_balance(t, id, time_at)integer balance at time_atNoneifiddid not exist attime_atNothing runs on a background timer. Instead, time advances lazily whenever any method is called at
timestamp = t. Before that method runs its own logic—even if the call itself will fail or only read data—we first execute every pending scheduled transfer whosedue <= t, stamping each executed transfer's balance change with its due time (nott):Timeline (from Example 1): t = 10: schedule_transfer(10, "ops", "eng", 40, delay=6) -> queued for due = 16 t = 11..17: (no method calls arrive at or after 16 yet) t = 18: get_balance(18, "eng", time_at=15) arrives! 1. _catch_up(18) sees due = 16 <= 18 -> runs transfer at effective time 16 2. Now query "eng" at time_at = 15 -> sees balance BEFORE time 16 (160)!Starting every public method with
self._catch_up(timestamp)guarantees the ledger is always synchronized up totimestamp.Model one workspace lifetime and its append-only history
Instead of storing bare integers in a dictionary like
balances["eng"] = 250, give each account its ownWorkspaceobject and route every balance mutation through one helper method,change(timestamp, delta).Why build this up front? Because timestamps never move backward. Every time
changeupdatesself.balance, it appends(timestamp, self.balance)to two parallel arrays (self.timesandself.balances). Point-in-time historical queries can then read those sorted arrays directly without replaying transactions.What if
"ads"is merged away att = 15and created again att = 17(as in Example 2)? Those are two separate lifetimes of"ads".WorkspaceManagermaintains: -self.workspaces: only the currently activeWorkspacefor each ID, forO(1)lookup. -self.lives: a chronological list of everyWorkspacelifetime ever created under that ID, so retired lifetimes remain queryable after a merge.from typing import Dict, List, Optional, Set class Workspace: """Represents one lifetime of a workspace ID: its live balance, history, and pending transfers.""" def __init__(self, workspace_id: str, created_at: int): self.id = workspace_id self.balance = 0 self.created_at = created_at self.removed_at: Optional[int] = None self.times: List[int] = [created_at] self.balances: List[int] = [0] self.pending: Set[str] = set() def change(self, timestamp: int, delta: int) -> int: """Apply a signed balance change at `timestamp` and append a history record.""" self.balance += delta self.times.append(timestamp) self.balances.append(self.balance) return self.balance class WorkspaceManager: def create_workspace(self, timestamp: int, workspace_id: str) -> bool: self._catch_up(timestamp) if workspace_id in self.workspaces: return False workspace = Workspace(workspace_id, timestamp) self.workspaces[workspace_id] = workspace if workspace_id not in self.lives: self.lives[workspace_id] = [] self.lives[workspace_id].append(workspace) return True def add_credit(self, timestamp: int, workspace_id: str, amount: int) -> Optional[int]: self._catch_up(timestamp) workspace = self.workspaces.get(workspace_id) if workspace is None: return None return workspace.change(timestamp, amount)Implement atomic instant transfers and top-k ranking
An immediate
transferupdates two accounts. Subtracting fromsourcebefore confirmingtargetexists would leave credits missing whentarget_idis invalid. Validate every precondition first (both accounts active,source_id != target_id, andsource.balance >= amount), and only then callchangeon both endpoints. Notice the inclusive boundary:amount == source.balancesucceeds and leaves0.For
top_k, we want highest balances first, breaking ties byworkspace_idascending ("core"before"ml"). Python compares tuples left to right in ascending order, so sorting(-balance, workspace_id)orders larger balances first while breaking ties alphabetically in one pass:Workspaces: "ml": 80, "ads": 0, "core": 80 Sort keys: (-80, "core"), (-80, "ml"), (0, "ads") Top 2: [("core", 80), ("ml", 80)]from typing import List, Optional, Tuple class WorkspaceManager: def transfer(self, timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: self._catch_up(timestamp) source = self.workspaces.get(source_id) target = self.workspaces.get(target_id) # Validate every precondition before mutating either balance (all-or-nothing update) if source is None or target is None or source_id == target_id: return None if source.balance < amount: return None new_source_balance = source.change(timestamp, -amount) target.change(timestamp, amount) return new_source_balance def top_k(self, timestamp: int, k: int) -> List[Tuple[str, int]]: self._catch_up(timestamp) if k <= 0: return [] # Negate balance so standard ascending sort puts largest balances first and breaks ties by ID ranked: List[Tuple[int, str]] = [] for workspace in self.workspaces.values(): ranked.append((-workspace.balance, workspace.id)) ranked.sort() result: List[Tuple[str, int]] = [] for negative_balance, workspace_id in ranked[:k]: result.append((workspace_id, -negative_balance)) return resultSchedule and cancel delayed transfers with a min-heap
Scanning every scheduled transfer ever created on each call would take
O(total transfers)per call. Instead, push pending transfers into a min-heap (heapq), a priority queue stored in a list wherequeue[0]is always the minimum tuple and push/pop each takeO(log q)time.We push
(due_time, creation_number, transfer_id)onto the heap: 1.due_timeruns earliest-due transfers first. 2.creation_number(an integer1, 2, ..., 10, ...) breaks ties in creation order. Never break ties using the stringtransfer_iddirectly—lexicographically,"transfer10" < "transfer2"because'1' < '2', which would execute the 10th transfer ahead of the 2nd!When
cancel_transferis called, deleting from the middle of a binary heap would costO(q). Instead, use lazy deletion: marktransfer.status = "canceled"inO(1)time and leave the tuple inside the heap. When_catch_upeventually pops that entry, it seestransfer.status != "pending"and skips it.Heap entries: [(due=12, seq=1, "transfer1"), (due=12, seq=2, "transfer2")] - At t = 12, _catch_up(12) pops (12, 1, "transfer1") -> "pending": core 80 -> 30, ads 0 -> 50 - Next pops (12, 2, "transfer2") -> "pending", but core has 30 < 50 -> status = "failed"!Each
Workspacealso keepsself.pending(the set of pendingtransfer_ids involving it as sender or receiver) so account merges can cancel affected transfers without scanning the entire heap.import heapq from typing import Dict, List, Optional, Tuple class ScheduledTransfer: """Tracks one scheduled transfer and its lifecycle state.""" def __init__(self, transfer_id: str, source_id: str, target_id: str, amount: int, due: int): self.id = transfer_id self.source_id = source_id self.target_id = target_id self.amount = amount self.due = due self.status = "pending" class WorkspaceManager: def _catch_up(self, timestamp: int) -> None: """Execute every pending scheduled transfer with due <= timestamp before handling a call.""" while self.queue and self.queue[0][0] <= timestamp: due, _, transfer_id = heapq.heappop(self.queue) transfer = self.transfers[transfer_id] # Lazy deletion: skip heap entries that were canceled after being pushed if transfer.status != "pending": continue self._finish(transfer) source = self.workspaces[transfer.source_id] target = self.workspaces[transfer.target_id] if source.balance < transfer.amount: transfer.status = "failed" continue source.change(due, -transfer.amount) target.change(due, transfer.amount) transfer.status = "executed" def _finish(self, transfer: ScheduledTransfer) -> None: """Remove a transfer from both endpoints' pending sets once it leaves 'pending' status.""" for workspace_id in (transfer.source_id, transfer.target_id): workspace = self.workspaces.get(workspace_id) if workspace is not None: workspace.pending.discard(transfer.id) def _cancel(self, transfer: ScheduledTransfer) -> None: """Mark a pending transfer canceled; its heap entry will be ignored lazily when popped.""" transfer.status = "canceled" self._finish(transfer) def schedule_transfer(self, timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: self._catch_up(timestamp) source = self.workspaces.get(source_id) target = self.workspaces.get(target_id) if source is None or target is None or source_id == target_id: return None self.transfer_count += 1 transfer_id = "transfer" + str(self.transfer_count) due_time = timestamp + delay transfer = ScheduledTransfer(transfer_id, source_id, target_id, amount, due_time) self.transfers[transfer_id] = transfer heapq.heappush(self.queue, (due_time, self.transfer_count, transfer_id)) source.pending.add(transfer_id) target.pending.add(transfer_id) return transfer_id def cancel_transfer(self, timestamp: int, transfer_id: str) -> bool: self._catch_up(timestamp) transfer = self.transfers.get(transfer_id) if transfer is None or transfer.status != "pending": return False self._cancel(transfer) return TrueMerge accounts in the exact required order
When
merge_workspaces(timestamp, target_id, source_id)consolidatessourceintotarget, the step order matters: 1. Catch up totimestampfirst: any scheduled transfer withdue <= timestampexecutes normally prior to the merge. 2. Validate: bothtargetandsourcemust be active and distinct (target_id != source_id). 3. Cancel remaining pending transfers touchingsource: iterate overlist(source.pending)(a snapshot copy, because_cancelmutatessource.pendingduring iteration!) and cancel each one. 4. Credittarget: addsource.balancetotargetattimestampviatarget.change(timestamp, source.balance). 5. Retiresource: setsource.removed_at = timestampand deletesource_idfromself.workspaces, while keepingsourceinsideself.lives[source_id]for historical lookups.Before merge at t = 15 (Example 2): workspaces: {"core": Core1, "ads": Ads1, "ml": Ml1} lives: {"core": [Core1], "ads": [Ads1], "ml": [Ml1]} After merge_workspaces(15, "core", "ads") and create_workspace(17, "ads"): workspaces: {"core": Core1, "ads": Ads2, "ml": Ml1} <- active lookups hit Ads2 lives["ads"]: [Ads1 (active [2, 15)), Ads2 (active [17, ...))]class WorkspaceManager: def merge_workspaces(self, timestamp: int, target_id: str, source_id: str) -> bool: self._catch_up(timestamp) target = self.workspaces.get(target_id) source = self.workspaces.get(source_id) if target is None or source is None or target_id == source_id: return False # Copy `source.pending` into a list because `_cancel` removes items from `source.pending` for transfer_id in list(source.pending): self._cancel(self.transfers[transfer_id]) target.change(timestamp, source.balance) source.removed_at = timestamp del self.workspaces[source_id] return TrueAnswer historical balances with binary search
Why is
workspace.timesguaranteed to remain sorted even when delayed transfers record updates atdue? Suppose the prior call was att = 12, a scheduled transfer is due at16, and the next call arrives att = 18. Every entry recorded so far has timestamp<= 12;_catch_up(18)records the due transfer at16(>= 12); then the call at18records any new change at18(>= 16). Timestamps inself.timesnever decrease!To evaluate
balance_at(time_at)on oneWorkspacelifetime: 1. Check whethertime_atlies in[created_at, removed_at): iftime_at < created_at, orremoved_at is not None and time_at >= removed_at, returnNone. 2. Locate the last entry with timestamp<= time_atusingbisect_right(self.times, time_at) - 1. Usingbisect_right(rather thanbisect_left) steps past all updates stamped attime_at, which handles cases where a due transfer and a direct deposit share the exact same timestampt = 7:times: [ 1, 5, 7, 7, 12 ] balances: [ 0, 30, 5, 9, 20 ] ^ bisect_right(times, 7) returns index 4 -> index 4 - 1 = 3 -> balances[3] = 9from bisect import bisect_right from typing import Optional class Workspace: def balance_at(self, time_at: int) -> Optional[int]: """Return the balance at `time_at`, or None if this lifetime was not active then.""" if time_at < self.created_at: return None if self.removed_at is not None and time_at >= self.removed_at: return None last_index = bisect_right(self.times, time_at) - 1 return self.balances[last_index] class WorkspaceManager: def get_balance(self, timestamp: int, workspace_id: str, time_at: int) -> Optional[int]: self._catch_up(timestamp) if time_at > timestamp: return None for workspace in self.lives.get(workspace_id, []): balance = workspace.balance_at(time_at) if balance is not None: return balance return NoneWalk through Example 1 end to end
Tracing Example 1's 12 calls shows how
_catch_up,times/balances, andremoved_atinteract:Call State changes Returns --------------------------------------------------------------------------------------------------- create_workspace(2, "eng") eng1: times=[2], balances=[0] True create_workspace(4, "ops") ops1: times=[4], balances=[0] True add_credit(5, "eng", 250) eng1: times=[2,5], balances=[0,250] 250 transfer(8, "eng", "ops", 90) eng1: +[(8, 160)], ops1: +[(8, 90)] 160 schedule_transfer(10,"ops","eng",40,6) queue=[(16, 1, "transfer1")] "transfer1" top_k(12, 2) due=16 > 12; (-160,"eng"), (-90,"ops") [("eng",160),("ops",90)] get_balance(18, "eng", 15) _catch_up(18) runs transfer1 at due=16: ops1: +[(16, 50)], eng1: +[(16, 200)] eng1 at 15 -> bisect_right([2,5,8,16],15)-1 = 2 160 get_balance(19, "eng", 16) eng1 at 16 -> bisect_right([2,5,8,16],16)-1 = 3 200 merge_workspaces(20, "eng", "ops") eng1: +[(20, 250)], ops1.removed_at=20 True get_balance(21, "ops", 19) ops1 active on [4, 20); at 19 -> 50 50 get_balance(22, "ops", 20) 20 >= ops1.removed_at (20) None top_k(25, 3) only eng1 remains in self.workspaces [("eng", 250)]Complete solution
from typing import Dict, List, Optional, Set, Tuple from bisect import bisect_right import heapq class Workspace: """Represents one lifetime of a workspace ID: its live balance, history, and pending transfers.""" def __init__(self, workspace_id: str, created_at: int): self.id = workspace_id self.balance = 0 self.created_at = created_at # Timestamp when this workspace was merged away, or None while still active self.removed_at: Optional[int] = None # Parallel history arrays: times[i] is the timestamp that produced balances[i] # Example: times = [1, 3, 4], balances = [0, 100, 70] (timestamps never decrease) self.times: List[int] = [created_at] self.balances: List[int] = [0] # Set of transfer IDs (e.g. {"transfer1", "transfer2"}) still pending for this workspace self.pending: Set[str] = set() def change(self, timestamp: int, delta: int) -> int: """Apply a signed balance change at `timestamp` and append a history record.""" self.balance += delta self.times.append(timestamp) self.balances.append(self.balance) return self.balance def balance_at(self, time_at: int) -> Optional[int]: """Return the balance at `time_at`, or None if this lifetime was not active then.""" # Before creation, this lifetime did not exist yet if time_at < self.created_at: return None # Uses >= because a merged workspace stops existing at the exact merge timestamp if self.removed_at is not None and time_at >= self.removed_at: return None # bisect_right lands right after all entries <= time_at, so index - 1 is the latest balance # even when several changes happened at the exact same timestamp last_index = bisect_right(self.times, time_at) - 1 return self.balances[last_index] class ScheduledTransfer: """Tracks one scheduled transfer and its lifecycle state.""" def __init__(self, transfer_id: str, source_id: str, target_id: str, amount: int, due: int): self.id = transfer_id self.source_id = source_id self.target_id = target_id self.amount = amount self.due = due # Starts as "pending", then transitions once to "executed", "failed", or "canceled" self.status = "pending" class WorkspaceManager: """In-memory credit ledger supporting transfers, top-k, scheduled transfers, merges, and history.""" def __init__(self): # Active workspaces only: {"A": Workspace("A", 1), ...} self.workspaces: Dict[str, Workspace] = {} # Every lifetime of every ID in chronological order: {"B": [old_B, recreated_B]} self.lives: Dict[str, List[Workspace]] = {} # All scheduled transfers ever created: {"transfer1": ScheduledTransfer(...)} self.transfers: Dict[str, ScheduledTransfer] = {} # Min-heap of (due_time, creation_number, transfer_id), e.g. [(10, 1, "transfer1")] # Integer creation_number breaks ties cleanly ("transfer2" before "transfer10") self.queue: List[Tuple[int, int, str]] = [] self.transfer_count = 0 # ---- shared helpers ------------------------------------------------------------------------ def _catch_up(self, timestamp: int) -> None: """Execute every pending scheduled transfer with due <= timestamp before handling a call.""" # Uses <= because transfers due at `timestamp` must run before the call at `timestamp` while self.queue and self.queue[0][0] <= timestamp: due, _, transfer_id = heapq.heappop(self.queue) transfer = self.transfers[transfer_id] # Lazy deletion: skip heap entries that were canceled after being pushed if transfer.status != "pending": continue self._finish(transfer) source = self.workspaces[transfer.source_id] target = self.workspaces[transfer.target_id] # Funds are checked at execution time; insufficient balance fails without partial debit if source.balance < transfer.amount: transfer.status = "failed" continue # Record changes at `due` (not the caller's `timestamp`) so past balance queries are exact source.change(due, -transfer.amount) target.change(due, transfer.amount) transfer.status = "executed" def _finish(self, transfer: ScheduledTransfer) -> None: """Remove a transfer from both endpoints' pending sets once it leaves 'pending' status.""" for workspace_id in (transfer.source_id, transfer.target_id): workspace = self.workspaces.get(workspace_id) if workspace is not None: workspace.pending.discard(transfer.id) def _cancel(self, transfer: ScheduledTransfer) -> None: """Mark a pending transfer canceled; its heap entry will be ignored lazily when popped.""" transfer.status = "canceled" self._finish(transfer) # ---- Part 1 -------------------------------------------------------------------------------- def create_workspace(self, timestamp: int, workspace_id: str) -> bool: self._catch_up(timestamp) if workspace_id in self.workspaces: return False workspace = Workspace(workspace_id, timestamp) self.workspaces[workspace_id] = workspace if workspace_id not in self.lives: self.lives[workspace_id] = [] self.lives[workspace_id].append(workspace) return True def add_credit(self, timestamp: int, workspace_id: str, amount: int) -> Optional[int]: self._catch_up(timestamp) workspace = self.workspaces.get(workspace_id) if workspace is None: return None return workspace.change(timestamp, amount) # ---- Part 2 -------------------------------------------------------------------------------- def transfer(self, timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: self._catch_up(timestamp) source = self.workspaces.get(source_id) target = self.workspaces.get(target_id) # Validate every precondition before mutating either balance (all-or-nothing update) if source is None or target is None or source_id == target_id: return None if source.balance < amount: return None new_source_balance = source.change(timestamp, -amount) target.change(timestamp, amount) return new_source_balance def top_k(self, timestamp: int, k: int) -> List[Tuple[str, int]]: self._catch_up(timestamp) if k <= 0: return [] # Negate balance so standard ascending sort puts largest balances first and breaks ties by ID ranked: List[Tuple[int, str]] = [] for workspace in self.workspaces.values(): ranked.append((-workspace.balance, workspace.id)) ranked.sort() result: List[Tuple[str, int]] = [] for negative_balance, workspace_id in ranked[:k]: result.append((workspace_id, -negative_balance)) return result # ---- Part 3 -------------------------------------------------------------------------------- def schedule_transfer(self, timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: self._catch_up(timestamp) source = self.workspaces.get(source_id) target = self.workspaces.get(target_id) if source is None or target is None or source_id == target_id: return None # Only valid requests consume a sequential transfer ID self.transfer_count += 1 transfer_id = "transfer" + str(self.transfer_count) due_time = timestamp + delay transfer = ScheduledTransfer(transfer_id, source_id, target_id, amount, due_time) self.transfers[transfer_id] = transfer heapq.heappush(self.queue, (due_time, self.transfer_count, transfer_id)) # Index on both workspaces so merge_workspaces can cancel in O(pending for source) source.pending.add(transfer_id) target.pending.add(transfer_id) return transfer_id def cancel_transfer(self, timestamp: int, transfer_id: str) -> bool: self._catch_up(timestamp) transfer = self.transfers.get(transfer_id) if transfer is None or transfer.status != "pending": return False self._cancel(transfer) return True # ---- Part 4 -------------------------------------------------------------------------------- def merge_workspaces(self, timestamp: int, target_id: str, source_id: str) -> bool: self._catch_up(timestamp) target = self.workspaces.get(target_id) source = self.workspaces.get(source_id) if target is None or source is None or target_id == source_id: return False # Copy `source.pending` into a list because `_cancel` removes items from `source.pending` for transfer_id in list(source.pending): self._cancel(self.transfers[transfer_id]) # Move remaining credit to target at `timestamp`, then retire `source` from active lookup target.change(timestamp, source.balance) source.removed_at = timestamp del self.workspaces[source_id] return True def get_balance(self, timestamp: int, workspace_id: str, time_at: int) -> Optional[int]: self._catch_up(timestamp) if time_at > timestamp: return None # Lifetimes for the same ID never overlap, so at most one lifetime covers `time_at` for workspace in self.lives.get(workspace_id, []): balance = workspace.balance_at(time_at) if balance is not None: return balance return None✅ Submit now — all tests should pass.
Intuition & how it works
Think of WorkspaceManager like a paper bank passbook paired with a desk calendar of future payment reminders—with no background clock ticking on its own. Because code runs only when a caller invokes a method at some timestamp, time advances lazily on demand: at the beginning of every call, we flip through the calendar up to timestamp, settle any reminders whose due date has arrived, and record each balance change on its own dated line in the account's passbook.
A naive implementation might scan every scheduled transfer ever created on each call, scan every transfer again during a merge, and clone a full dictionary of all balances after every edit to support historical lookups. That passes tiny examples, but as accounts, transfers, and edits scale into the thousands, scanning all transfers per call turns linear workloads into quadratic work, and full-state snapshots blow up memory. Instead, we combine three classic data structures:
- A min-heap (a priority queue where the smallest item always sits at index 0 and insertion or removal takes logarithmic time) ordered by (due_time, creation_number) so we inspect only transfers that are actually due.
- Lazy deletion (updating a canceled item's status flag immediately instead of hunting through the heap to remove it, then skipping it when it eventually pops) paired with a per-account pending set so canceling or merging never touches unrelated transfers.
- Per-account sorted (times, balances) arrays queried with binary search (repeatedly halving a sorted array to locate a target position in logarithmic steps via bisect_right), storing retired lifetimes in a lives list so merged-and-recreated IDs stay cleanly separated.
Trace four steps from Example 1 to watch all three structures cooperate:
1. create_workspace(2, "eng"), add_credit(5, "eng", 250), and transfer(8, "eng", "ops", 90) record eng.times = [2, 5, 8] and eng.balances = [0, 250, 160], with ops.balances = [0, 90].
2. schedule_transfer(10, "ops", "eng", 40, delay=6) pushes (16, 1, "transfer1") onto the min-heap; "ops" still holds 90 because funds are checked at execution rather than scheduling.
3. get_balance(18, "eng", time_at=15) arrives at t = 18: first _catch_up(18) pops "transfer1" and stamps its +40 change at due time 16, making eng.times = [2, 5, 8, 16] and eng.balances = [0, 250, 160, 200]. Binary search for time_at = 15 lands on index 2 (t = 8) and returns 160.
4. get_balance(19, "eng", time_at=16) searches eng.times for 16, lands on index 3, and returns 200.
Complexity
Let n be the number of currently active workspaces, q the number of entries in the scheduled-transfer heap, h the number of balance updates recorded on one workspace lifetime, p the number of pending transfers touching one workspace, and L the number of lifetimes created under one ID.
create_workspace,add_credit,transfer:O(1)average time beyond_catch_up, because each performs a constant number of dictionary lookups and appends one entry totimesandbalances.top_k:O(n log n)time andO(n)temporary space beyond_catch_up, because we build one(-balance, id)tuple for each of thenactive accounts and sort them.schedule_transferandcancel_transfer:schedule_transfertakesO(log q)time to push one tuple onto the min-heap plusO(1)dictionary and set insertions.cancel_transfertakesO(1)time beyond_catch_upbecause it flipstransfer.statusand discards the ID from twopendingsets without scanning the heap._catch_up(amortized across calls): Each scheduled transfer is pushed once and popped at most once, so acrossStotal scheduled transfers the cumulative heap cost isO(S log S), orO(log q)amortized per scheduled transfer.merge_workspaces:O(p)time beyond_catch_up, because we loop directly over theptransfer IDs insource.pendingrather than scanning every transfer ever scheduled.get_balance:O(L + log h)time beyond_catch_up. Checking each lifetime's[created_at, removed_at)window takesO(1), and because lifetimes of the same ID never overlap in time, at most one lifetime runsbisect_rightinO(log h)steps.- Space:
O(C + S)total memory, whereCis the total number of balance-changing events andSis the total number of scheduled transfers stored inself.transfers.
Edge cases
- Duplicate vs. recreated workspace IDs: Calling
create_workspaceon a currently active ID returnsFalse, whereas calling it on an ID retired by a prior merge starts a freshWorkspacelifetime at balance0with independent history. - Transfer boundaries: Self-transfers (
source_id == target_id), unknown IDs, andamount > source.balancereturnNonewith zero side effects;amount == source.balancesucceeds and leaves0. top_kbounds and ties: Tied balances break alphabetically byworkspace_idascending;kexceeding the active count returns all active workspaces, andk <= 0returns[].- Cancel at the exact due time: Because
_catch_up(timestamp)executes transfers withdue <= timestampfirst,cancel_transfer(12, "transfer1")for a transfer due at12arrives after execution and returnsFalse. - Simultaneous due transfers: Transfers due at the same timestamp execute in creation order; an earlier transfer can spend the sender's balance and cause a later transfer at the same due time to transition to
"failed". - Multiple updates at the same timestamp: When a scheduled transfer due at
t = 7executes right beforeadd_credit(7, ...),timescontains two7s;bisect_right(times, 7) - 1selects the final entry at7soget_balance(..., time_at=7)reflects both changes. - Existence boundaries around a merge: An account created at
4and merged away at20covers the half-open interval[4, 20)(an interval including its start point4and excluding its end point20), soget_balancereturns0at4andNoneat20.
Common mistakes
- Skipping
_catch_upon read-only or failing calls: Even whencancel_transferortransferfails, ortop_konly reads balances, pending transfers due at or beforetimestampmust execute first. - Mutating the sender before validating the receiver: Subtracting from
sourcebefore checkingtargetleaves a partial debit whentargetis invalid; always enforce an all-or-nothing (atomic) update (an operation that either applies every part or changes nothing). - Recording scheduled transfers at
timestampinstead ofdue: Stamping a transfer due at16with the caller'stimestamp = 18corruptsget_balancequeries fortime_at = 16andtime_at = 17. - Breaking heap ties with the string ID: Comparing
"transfer10"and"transfer2"lexicographically puts"transfer10"first because'1' < '2'; always include the integerself.transfer_countin the heap tuple. - Mutating
source.pendingwhile iterating over it:_cancelremoves transfer IDs fromsource.pending, so looping oversource.pendingdirectly raisesRuntimeError: Set changed size during iteration; iterate overlist(source.pending)instead. - Keying history only by
workspace_id: Storing one flat history list per ID leaks a retired account's balances into a recreated account with the same ID, or returns stale balances during the inactive gap[removed_at, recreated_at).
Alternative approaches
- Global append-only event log: Record every operation
(time, kind, args)in one list and replay events up totime_aton eachget_balancecall. Simple to write, butget_balancedegrades toO(total events)per query instead ofO(log h). - Linear scan of scheduled transfers on
_catch_up: Scanning a list of all scheduled transfers fordue <= timestampworks on tiny inputs, but costsO(S)on every method call rather thanO(log q)per due transfer with a min-heap.
Follow-up questions
- Suppose read-heavy workloads invoke
top_korders of magnitude more frequently than balance mutations. How can you servetop_kwithout re-sorting all active accounts each time? The lightest change is a dirty-flag cache: materialize the sorted[(id, balance), ...]list once, invalidate it only when a balance mutates or an account is created or merged, and serve repeatedtop_kcalls by slicingcached[:k]inO(k)time. When both reads and writes are frequent, maintain active accounts inside an order-statistic tree or balanced BST (such assortedcontainers.SortedList) keyed by(-balance, id): each balance update removes the old key and inserts the new key inO(log n)time, whiletop_kiterates the firstkentries inO(k)time. - During
merge_workspaces, how do you invalidate pending scheduled transfers involving the retiring account in time proportional to only its own active transfers? Maintain a per-accountpending: Set[str]index on everyWorkspaceinstance: inserttransfer_idinto bothsource.pendingandtarget.pendingduringschedule_transfer, and discard it from both endpoints whenever a transfer executes, fails, or is canceled. Duringmerge_workspaces, iterate overlist(source.pending)inO(p)time and mark each transfer"canceled", relying on lazy deletion to skip its stale heap entry later without scanning the global transfer table or heap. - Which invariants fail if incoming requests no longer have strictly increasing timestamps (allowing ties or out-of-order arrivals), and how would you adapt the data structures? Equal timestamps already work unchanged:
_catch_upuses<=, same-time updates append in arrival order, andbisect_rightselects the final balance attime_at. Out-of-order (decreasing) timestamps violate three invariants:timesis no longer sorted, a delayed transfer att = 12may have already failed for insufficient funds before an earlier deposit att = 9arrives, and a cancel att = 11could arrive after execution att = 12. To support out-of-order events, either reject calls older than the latest processed timestamp, buffer incoming calls behind a bounded watermark (a moving timestamp frontier guaranteeing no older events will be accepted), or store an event log ordered by event time and recompute state forward from the insertion point when late events arrive. - How would you synchronize
WorkspaceManagerso multi-threaded callers can execute operations safely without data races or deadlocks? Start with a single coarse-grained mutex around every public method, assigning or verifying monotonic timestamps inside the critical section so threads cannot interleave out of timestamp order. If lock contention becomes a bottleneck on instanttransfercalls after catching up, acquire per-account locks in canonical ID order (min(source_id, target_id)beforemax(source_id, target_id)) to prevent deadlock (a cycle where two threads wait forever on each other's locks), while serializing global operations like_catch_up,merge_workspaces, andtop_kunder a reader-writer lock or single-writer command queue.
Follow-up questions
- Suppose read-heavy workloads invoke `top_k` orders of magnitude more frequently than balance mutations. How can you serve `top_k` without re-sorting all active accounts each time?
- During `merge_workspaces`, how do you invalidate pending scheduled transfers involving the retiring account in time proportional to only its own active transfers?
- Which invariants fail if incoming requests no longer have strictly increasing timestamps (allowing ties or out-of-order arrivals), and how would you adapt the data structures?
- How would you synchronize `WorkspaceManager` so multi-threaded callers can execute operations safely without data races or deadlocks?
Similar questions
- Points Ledger with Deferred Transfers
- In-Memory File Store with Quotas and Resizing
- High-Concurrency Account Ledger Service Design
- Staged File Storage with Quotas and Snapshots
- Bank Ledger with Delayed Payments and Account Consolidation
- Stateful Shift Hours and Compensation Ledger
More Airbnb interview questions
- Workspace Credit Ledger With Rankings and Scheduled Transfers Medium
- Multi-Stage In-Memory Ledger with Scheduled Settlements and Merges Hard
- Find Valid Split-Stay Listing Pairs Medium Pro
- Granular Project Review: Milestones, Architecture, and Impact Medium Pro
- Cross-Team Execution, Collaboration, and Core Values Hard Pro
- Compute City-Level Median Listing Prices Medium Pro
- In-Memory File Store with Quotas and Resizing Medium Pro
- Personalized Rental Search with User and Property Embeddings Medium Pro
- Classifying Kid-Suitable Vacation Rentals for Search Filtering Medium Pro
- Bank Ledger with Delayed Payments and Account Consolidation Medium Pro