Workspace Credit Ledger With Rankings and Scheduled Transfers
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Build an in-memory credit ledger that tracks named workspaces across a sequence of timestamped commands, supporting account creation, deposits, immediate transfers, balance rankings, and cancellable deferred transfers.
def workspace_credit_system(operations: List[str], arguments: List[List]) -> List:
You receive two equal-length lists: operations[i] names the command to run, and arguments[i] supplies its parameters, always starting with an integer timestamp (arguments[i][0]). Timestamps across the call list are non-decreasing. Execute all commands sequentially on a single ledger instance and return a list containing one result per command.
Catch-Up Rule
Before running any command at timestamp—including read-only rankings and cancellations—first process every still-pending scheduled transfer whose execute_at <= timestamp. Due transfers must execute in ascending execute_at order, breaking ties by ascending transfer_id.
Supported Commands
"create"—[timestamp, workspace_id]- Registers a new workspace starting at
0credits and returnsTrue. - If
workspace_idalready exists, leaves state unchanged and returnsFalse.
- Registers a new workspace starting at
"add"—[timestamp, workspace_id, amount]- Adds
amountcredits toworkspace_idand returnsTrue. - If
workspace_iddoes not exist oramount <= 0, leaves state unchanged and returnsFalse.
- Adds
"transfer"—[timestamp, source, target, amount]- Atomically moves
amountcredits fromsourcetotargetand returnsTrue. - Returns
Falsewithout modifying any balance if either workspace ID is unknown,source == target,amount <= 0, orsourcecurrently has fewer thanamountcredits.
- Atomically moves
"top_k"—[timestamp, k]- Returns a
List[str]of up tokworkspace IDs sorted by current credit balance descending, breaking ties byworkspace_idin ascending lexicographical order. - Returns
[]whenk <= 0or zero workspaces exist; returns all existing workspace IDs in ranked order whenkexceeds the workspace count.
- Returns a
"schedule"—[timestamp, source, target, amount, execute_at]- Registers a future transfer of
amountcredits fromsourcetotargetscheduled forexecute_at. - Returns
None(without consuming a transfer ID) if either workspace ID is unknown,source == target,amount <= 0, orexecute_at <= timestamp. Current credit insourceis not checked at scheduling time. - Each valid
"schedule"call assigns and returns the next 1-based sequential integertransfer_id(1, 2, 3, ...). - When
execute_atarrives during catch-up,amountmoves fromsourcetotargetifsourceholds at leastamountcredits at that moment; otherwise no credits move and the transfer permanently fails (it is never retried and can no longer be cancelled).
- Registers a future transfer of
"cancel"—[timestamp, workspace_id, transfer_id]- Cancels
transfer_idand returnsTrueif and only ifworkspace_idexists,transfer_idexists,workspace_idis the transfer'ssource, and the transfer remains pending after catching up totimestamp. Otherwise returnsFalse.
- Cancels
Examples
Example 1
Input:
operations = ["create", "create", "add", "transfer", "transfer", "top_k"]
arguments = [[1, "ops"], [2, "eng"], [3, "ops", 80], [4, "ops", "eng", 40], [5, "eng", "sales", 10], [6, 5]]
Output: [True, True, True, True, False, ["eng", "ops"]]
"ops" receives 80 credits and sends 40 to "eng". Sending 10 to unknown workspace "sales" fails cleanly, leaving "eng" and "ops" tied at 40 ("eng" ranks ahead of "ops" alphabetically, and k = 5 returns all existing workspaces).
Example 2
Input:
operations = ["create", "create", "add", "schedule", "top_k", "top_k"]
arguments = [[2, "core"], [3, "data"], [5, "core", 90], [6, "core", "data", 60, 15], [12, 2], [15, 2]]
Output: [True, True, True, 1, ["core", "data"], ["data", "core"]]
Transfer 1 (60 credits from "core" to "data", due at 15) has not fired yet at t = 12 (core = 90, data = 0), so "core" leads. At t = 15, catch-up runs before "top_k", shifting balances to core = 30, data = 60 so "data" moves into first place.
Example 3
Input:
operations = ["create", "create", "add", "schedule", "cancel", "cancel", "top_k"]
arguments = [[1, "web"], [2, "api"], [3, "web", 50], [4, "web", "api", 35, 12], [7, "api", 1], [8, "web", 1], [12, 2]]
Output: [True, True, True, 1, False, True, ["web", "api"]]
At t = 7, "api" cannot cancel transfer 1 because "web" is the sender (False). At t = 8, "web" cancels transfer 1 before its due timestamp 12 (True), so "web" retains all 50 credits at t = 12.
Constraints
1 <= len(operations) == len(arguments) <= 10^50 <= timestamp <= 10^9, and timestamps are non-decreasing across consecutive operations.- Workspace identifiers are non-empty ASCII strings.
-10^9 <= amount, k, execute_at, transfer_id <= 10^9
Step-by-step walkthrough
Pin down the interface and edge-case rules
In a multi-level coding assessment, your top priority is designing a clean class interface whose earlier methods never break when later levels are added. Every operation in
workspace_credit_system(operations, arguments)starts with an integertimestamp:Operation Arguments Return value create[ts, workspace_id]Trueif created at balance0;Falseif ID already existsadd[ts, workspace_id, amount]Trueif added;Falseif ID is unknown oramount <= 0transfer[ts, source, target, amount]Trueif moved;Falseon invalid IDs, self-transfer,amount <= 0, or insufficient credittop_k[ts, k]Up to kworkspace IDs ordered by highest balance, ties broken by ID ascendingschedule[ts, source, target, amount, execute_at]Serial integer ID 1, 2, 3, ...if valid andexecute_at > ts, elseNonecancel[ts, workspace_id, transfer_id]Trueifworkspace_id == sourceand the transfer is still pending atts, elseFalseKey behavioral contracts matching all samples:
- No negative balances and no partial writes: any rejected call leaves all state untouched (and a rejected
scheduledoes not consume atransfer_id). - Due transfers run before the call at
ts: every operation — including read-onlytop_k— first applies all pending transfers withexecute_at <= ts, ordered by(execute_at, transfer_id). - Credit is checked at execution time, not schedule time: if a due transfer's source lacks enough credit when
execute_atarrives, that transfer is marked"failed"and never retried.
- No negative balances and no partial writes: any rejected call leaves all state untouched (and a rejected
Choose the core data structures
Parts 1 and 2 only need a dictionary
balancesmappingworkspace_id -> credit. Part 3 introduces pending future work: scanning a plain list of allSscheduled transfers before every call would costO(S)per call (O(n * S)overall).Instead, we pair a dictionary of transfer records with a min-heap (
due_heap, a priority queue where index0is always the smallest item):balances: {"core": 90, "data": 0} transfers: { 1: {"source": "core", "target": "data", "amount": 35, "status": "cancelled"}, 2: {"source": "core", "target": "data", "amount": 60, "status": "pending"}, } due_heap: [(12, 1), (15, 2)] <-- sorted by (execute_at, transfer_id) ^ due_heap[0] is always the next transfer to inspect!Storing
(execute_at, transfer_id)tuples indue_heapsolves two problems at once:due_heap[0]tells us inO(1)time whether anything has come due (execute_at <= timestamp).- If two transfers share the exact same
execute_at, Python compares the second tuple element (transfer_id), automatically running the earlier-scheduled transfer first!
Part 1 · Validate everything before changing any balance
A transfer touches two workspaces and can fail for five reasons: unknown
source, unknowntarget,source == target,amount <= 0, orbalances[source] < amount. Subtracting fromsourcebefore checkingtargetwould corruptsource's balance whenevertargetis invalid.Splitting validation into
_valid_pair(structural checks shared withschedule) and_move(balance check shared with_catch_up) keeps every check atomic and reusable:def _valid_pair(self, source: str, target: str, amount: int) -> bool: """Check that source and target are distinct existing workspaces and amount is positive.""" if source not in self.balances or target not in self.balances: return False if source == target: return False return amount > 0 def _move(self, source: str, target: str, amount: int) -> bool: """Atomically move `amount` from `source` to `target` if `source` has enough credit.""" if self.balances[source] < amount: return False self.balances[source] -= amount self.balances[target] += amount return True def create(self, timestamp: int, workspace_id: str) -> bool: self._catch_up(timestamp) if workspace_id in self.balances: return False self.balances[workspace_id] = 0 return True def add(self, timestamp: int, workspace_id: str, amount: int) -> bool: self._catch_up(timestamp) if workspace_id not in self.balances or amount <= 0: return False self.balances[workspace_id] += amount return True def transfer(self, timestamp: int, source: str, target: str, amount: int) -> bool: self._catch_up(timestamp) # Validate both workspaces and amount BEFORE touching either balance. if not self._valid_pair(source, target, amount): return False return self._move(source, target, amount)Notice that every public method begins with
self._catch_up(timestamp). In Parts 1 and 2due_heapis empty so_catch_upreturns immediately; in Part 3 every method automatically sees up-to-date balances!Part 2 · Rank workspaces with a negated-balance tuple key
top_kwants highestbalancefirst, and alphabeticalworkspace_idascending on ties ("eng"before"ops"when both have40credits).Python compares tuples left to right in ascending order. By pairing
-balancewithworkspace_id, larger balances become more negative (smaller) numbers while IDs stay in normal alphabetical order:Workspaces: "ops": 40, "ml": 0, "eng": 40 Tuple keys (-balance, workspace_id): "eng" -> (-40, "eng") <-- smallest tuple (rank 1: tied at 40, "eng" < "ops") "ops" -> (-40, "ops") <-- second smallest (rank 2) "ml" -> ( 0, "ml") <-- largest tuple (rank 3)Using
heapq.nsmallest(k, ranking_keys)extracts the bestktuples inO(W log k)time forWworkspaces (and gracefully returns allWworkspaces whenk > W), whileif k <= 0: return []handles zero or negativek.def top_k(self, timestamp: int, k: int) -> List[str]: self._catch_up(timestamp) if k <= 0: return [] # Negate balance so Python's min-order ranks highest balance first, # while positive `workspace_id` breaks ties alphabetically ascending ("a" before "b"). ranking_keys = [] for workspace_id, balance in self.balances.items(): ranking_keys.append((-balance, workspace_id)) top_entries = heapq.nsmallest(k, ranking_keys) result = [] for neg_balance, workspace_id in top_entries: result.append(workspace_id) return resultPart 3 · Schedule transfers and cancel with lazy deletion
When
scheduleis called attimestamp:- Catch up due transfers up to
timestamp. - Verify
_valid_pair(source, target, amount)andexecute_at > timestamp(must be strictly in the future). ReturnNoneimmediately if anything is invalid sonext_transfer_idis not wasted. - Store the transfer dictionary with
"status": "pending"and push(execute_at, transfer_id)ontodue_heap.
When
cancelis called, removing(execute_at, transfer_id)directly from the middle ofdue_heapwould require anO(S)linear scan plus re-heapifying. Instead, we use lazy deletion: after catching up totimestamp, we check that the transfer is still"pending"and belongs toworkspace_id, and simply fliptransfer["status"] = "cancelled"inO(1)time. When(execute_at, transfer_id)eventually reaches the top ofdue_heap,_catch_upsees"cancelled"and discards it!def schedule( self, timestamp: int, source: str, target: str, amount: int, execute_at: int ) -> Optional[int]: self._catch_up(timestamp) # Require strictly future `execute_at > timestamp`; validate before consuming an ID. if not self._valid_pair(source, target, amount) or execute_at <= timestamp: return None transfer_id = self.next_transfer_id self.next_transfer_id += 1 self.transfers[transfer_id] = { "source": source, "target": target, "amount": amount, "status": "pending", } heapq.heappush(self.due_heap, (execute_at, transfer_id)) return transfer_id def cancel(self, timestamp: int, workspace_id: str, transfer_id: int) -> bool: # Catch up first: a transfer due at or before `timestamp` has already run and cannot be cancelled. self._catch_up(timestamp) if workspace_id not in self.balances: return False transfer = self.transfers.get(transfer_id) if transfer is None or transfer["status"] != "pending": return False if transfer["source"] != workspace_id: return False transfer["status"] = "cancelled" return True- Catch up due transfers up to
Catch up due transfers before every read and write
_catch_up(timestamp)pops fromdue_heapwhile the earliest due time satisfiesexecute_at <= timestamp:- If
status != "pending", it was cancelled earlier —continue. - Otherwise try
_move(source, target, amount). Ifsourcehas enough credit right now, the balances update immediately (so another transfer due at the same or a later timestamp sees the updated balances!) andstatusbecomes"done". Otherwisestatusbecomes"failed".
def _catch_up(self, timestamp: int) -> None: """Apply every pending transfer with execute_at <= timestamp in due-time order.""" # Use `<=` because transfers due at `timestamp` take effect BEFORE the call at `timestamp`. while self.due_heap and self.due_heap[0][0] <= timestamp: execute_at, transfer_id = heapq.heappop(self.due_heap) transfer = self.transfers[transfer_id] # Lazy deletion: cancelled transfers stay in `due_heap` and are skipped here in O(1). if transfer["status"] != "pending": continue # Credit is checked at execution time; insufficient credit drops the transfer permanently. if self._move(transfer["source"], transfer["target"], transfer["amount"]): transfer["status"] = "done" else: transfer["status"] = "failed"Finally,
workspace_credit_systeminstantiatesWorkspaceCredits()once and dispatches each(op, args)pair in order.- If
Trace Example 2 and competing scheduled transfers
First see how Example 2 shifts rankings right at
t = 15:"core"starts at90credits, schedules60to"data"forexecute_at = 15(transfer_id = 1), still leads["core", "data"]att = 12, and then_catch_up(15)moves the60credits beforetop_k(15, 2)runs, flipping the order to["data", "core"].Now trace a fuller scenario where two scheduled transfers compete for
"core"'s50credits alongside a cancellation:Call due_heap State after call Return -------------------------------------------------------------------------------------------------------- create(1,"core"), create(2,"data"), create(3,"ml"), add(4,"core", 50) [] core=50, data=0, ml=0 True.. schedule(5, "core","data", 50, 20) [(20, 1)] #1 pending (due at 20) 1 schedule(6, "core","ml", 50, 15) [(15, 2), (20, 1)] #2 sits at root (15 < 20!) 2 schedule(7, "core","data", 10, 18) [(15,2),(20,1),(18,3)] #3 pending (due at 18) 3 cancel(8, "core", 3) [(15,2),(20,1),(18,3)] #3 marked "cancelled" True top_k(20, 3) _catch_up(20) pops in heap order: 1. pop (15, 2): pending -> core=0, ml=50 (#2 "done") 2. pop (18, 3): "cancelled" -> skipped! 3. pop (20, 1): pending, core has 0 < 50 -> (#1 "failed") [] core=0, data=0, ml=50 ["ml","core","data"]Notice how
#2(scheduled second, but due earlier att = 15) ran before#1(due att = 20) and took"core"'s50credits, causing#1to fail cleanly att = 20.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq class WorkspaceCredits: def __init__(self): # balances: maps workspace_id -> int current credit, e.g. {"a": 60, "b": 40} self.balances: Dict[str, int] = {} # transfers: maps transfer_id -> {"source": str, "target": str, "amount": int, "status": str} # where status is one of "pending", "done", "failed", or "cancelled" self.transfers: Dict[int, Dict[str, Any]] = {} # due_heap: min-heap of (execute_at, transfer_id) so earliest due transfer is always at index 0; # transfer_id breaks same-timestamp ties in scheduling order. self.due_heap: List[Tuple[int, int]] = [] # next_transfer_id: 1-based serial ID incremented only when `schedule` succeeds self.next_transfer_id: int = 1 # ---- internal helpers ---- def _catch_up(self, timestamp: int) -> None: """Apply every pending transfer with execute_at <= timestamp in due-time order.""" # Use `<=` because transfers due at `timestamp` take effect BEFORE the call at `timestamp`. while self.due_heap and self.due_heap[0][0] <= timestamp: execute_at, transfer_id = heapq.heappop(self.due_heap) transfer = self.transfers[transfer_id] # Lazy deletion: cancelled transfers stay in `due_heap` and are skipped here in O(1). if transfer["status"] != "pending": continue # Credit is checked at execution time; insufficient credit drops the transfer permanently. if self._move(transfer["source"], transfer["target"], transfer["amount"]): transfer["status"] = "done" else: transfer["status"] = "failed" def _valid_pair(self, source: str, target: str, amount: int) -> bool: """Check that source and target are distinct existing workspaces and amount is positive.""" if source not in self.balances or target not in self.balances: return False if source == target: return False return amount > 0 def _move(self, source: str, target: str, amount: int) -> bool: """Atomically move `amount` from `source` to `target` if `source` has enough credit.""" if self.balances[source] < amount: return False self.balances[source] -= amount self.balances[target] += amount return True # ---- Part 1: Workspaces, credit, and instant transfers ---- def create(self, timestamp: int, workspace_id: str) -> bool: self._catch_up(timestamp) if workspace_id in self.balances: return False self.balances[workspace_id] = 0 return True def add(self, timestamp: int, workspace_id: str, amount: int) -> bool: self._catch_up(timestamp) if workspace_id not in self.balances or amount <= 0: return False self.balances[workspace_id] += amount return True def transfer(self, timestamp: int, source: str, target: str, amount: int) -> bool: self._catch_up(timestamp) # Validate both workspaces and amount BEFORE touching either balance. if not self._valid_pair(source, target, amount): return False return self._move(source, target, amount) # ---- Part 2: Top K workspaces ---- def top_k(self, timestamp: int, k: int) -> List[str]: self._catch_up(timestamp) if k <= 0: return [] # Negate balance so Python's min-order ranks highest balance first, # while positive `workspace_id` breaks ties alphabetically ascending ("a" before "b"). ranking_keys = [] for workspace_id, balance in self.balances.items(): ranking_keys.append((-balance, workspace_id)) top_entries = heapq.nsmallest(k, ranking_keys) result = [] for neg_balance, workspace_id in top_entries: result.append(workspace_id) return result # ---- Part 3: Scheduled and cancellable transfers ---- def schedule( self, timestamp: int, source: str, target: str, amount: int, execute_at: int ) -> Optional[int]: self._catch_up(timestamp) # Require strictly future `execute_at > timestamp`; validate before consuming an ID. if not self._valid_pair(source, target, amount) or execute_at <= timestamp: return None transfer_id = self.next_transfer_id self.next_transfer_id += 1 self.transfers[transfer_id] = { "source": source, "target": target, "amount": amount, "status": "pending", } heapq.heappush(self.due_heap, (execute_at, transfer_id)) return transfer_id def cancel(self, timestamp: int, workspace_id: str, transfer_id: int) -> bool: # Catch up first: a transfer due at or before `timestamp` has already run and cannot be cancelled. self._catch_up(timestamp) if workspace_id not in self.balances: return False transfer = self.transfers.get(transfer_id) if transfer is None or transfer["status"] != "pending": return False if transfer["source"] != workspace_id: return False transfer["status"] = "cancelled" return True def workspace_credit_system(operations: List[str], arguments: List[List]) -> List: system = WorkspaceCredits() results = [] # Dispatch each timestamped operation against the same stateful WorkspaceCredits instance. for op, args in zip(operations, arguments): if op == "create": results.append(system.create(args[0], args[1])) elif op == "add": results.append(system.add(args[0], args[1], args[2])) elif op == "transfer": results.append(system.transfer(args[0], args[1], args[2], args[3])) elif op == "top_k": results.append(system.top_k(args[0], args[1])) elif op == "schedule": results.append(system.schedule(args[0], args[1], args[2], args[3], args[4])) elif op == "cancel": results.append(system.cancel(args[0], args[1], args[2])) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a bank teller managing two things on their desk: a ledger binder (balances) listing every workspace's current credits, and a stack of post-dated transfer slips arranged by due date. To keep the earliest slip on top without re-sorting the whole stack every time, we store (execute_at, transfer_id) pairs in a min-heap — a tree-in-a-list priority queue (a collection that always exposes its smallest item first) where inserting or removing the earliest item takes O(log S) time. Whenever any request arrives at timestamp t — even a read-only top_k query — the teller first runs a _catch_up(t) step, popping and applying every slip with execute_at <= t before handling the new request. If a customer cancels a pending slip beforehand, we use lazy deletion: instead of digging through the middle of the heap to remove it, we simply mark transfers[id]["status"] = "cancelled" in O(1) time and skip the slip later when its due date reaches the top of the heap.
Why do the naive approaches fall short? Keeping scheduled transfers in a flat list and scanning all S entries before each of the n calls takes O(n * S) time, and deleting cancelled entries from the middle of a heap with list.remove plus heapify also degrades each cancel to O(S). Even on small inputs, two logical traps break correctness: forgetting to run _catch_up inside read-only calls like top_k returns stale rankings, and subtracting from source before checking whether target exists leaves half-applied balances when a transfer fails.
Here is a 5-step walkthrough building on "core" and "data" from Example 2:
1. create(2, "core"), create(3, "data"), add(5, "core", 90)
balances = {"core": 90, "data": 0}, due_heap = []
2. schedule(6, "core", "data", 60, 15) -> returns 1
due_heap = [(15, 1)], transfers[1] = {core->data, 60, "pending"}
3. schedule(7, "core", "data", 20, 18) -> returns 2
due_heap = [(15, 1), (18, 2)], transfers[2] = {core->data, 20, "pending"}
4. cancel(8, "core", 2) -> returns True
transfers[2]["status"] = "cancelled" (due_heap untouched!)
5. top_k(18, 2):
_catch_up(18) pops (15, 1) -> pending -> moves 60 (core=30, data=60, #1 "done")
_catch_up(18) pops (18, 2) -> "cancelled" -> skipped!
ranking keys: [(-60, "data"), (-30, "core")] -> returns ["data", "core"]
Complexity
Let W be the number of created workspaces, S be the number of successfully scheduled transfers, and n be the total number of operations.
create,add,transfer,cancel:O(1)average time for the dictionary lookups and status updates (excluding_catch_up).schedule:O(log S)time to push(execute_at, transfer_id)ontodue_heap(excluding_catch_up).top_k:O(W log k)time whenk < Wbecauseheapq.nsmallestscans allWworkspace keys while maintaining a bounded heap of sizek(orO(W log W)whenk >= W, where Python sorts theWkeys directly)._catch_upacross allncalls:O(S log S)total time, orO(log S)amortized time per scheduled transfer (meaning that although one single call might pop many due transfers at once, each of theStransfers is pushed ontodue_heaponce and popped at most once across the entire run).- Space:
O(W + S).balancesstoresWworkspaces,ranking_keystemporarily holdsWtuples duringtop_k, andtransfersplusdue_heapstore one entry per scheduled transfer (Sentries total).
Edge cases
- Unknown or duplicate workspace IDs: creating an existing ID or referencing a missing ID in any operation returns
False(Noneforschedule) without mutating state. - Self-transfers and non-positive amounts:
source == targetandamount <= 0are rejected in bothtransferandschedule;addalso rejectsamount <= 0. - Exact-balance transfer: transferring
amount == balances[source]succeeds and leaves0; requesting1more credit fails cleanly. top_kboundary sizes:k <= 0or zero created workspaces returns[];k > Wreturns allWworkspace IDs in ranked order.- Balance ties: broken deterministically by
workspace_idin ascending alphabetical order (including newly created workspaces tied at0). - Boundary timestamps (
execute_at == timestamp): inschedule,execute_at <= timestampis rejected as non-future; in_catch_up,execute_at <= timestampruns before the operation attimestamp, so callingcancelatt == execute_atreturnsFalsebecause the transfer has already run. - Same-timestamp due transfers: two transfers due at the same
execute_atexecute in scheduling order (transfer_idascending); if the first drains the source workspace, the second fails. - Insufficient credit at execution time: marked
"failed"permanently — never retried when credit is added later, and no longer cancellable.
Common mistakes
- Mutating
sourcebefore validatingtarget: subtractingbalances[source] -= amountbefore confirmingtarget in self.balancescorruptssourcewhentargetis missing. Check every precondition first. - Skipping
_catch_upintop_k: read operations must also advance pending transfers up totimestamp, ortop_kwill compute rankings on outdated balances. - Using
<instead of<=in_catch_up: writingdue_heap[0][0] < timestampdelays transfers due attimestampuntil after the call attimestamp. - Pushing
(balance, workspace_id)intoheapq: Python'sheapqis a min-heap, so un-negatedbalancereturns the poorest workspaces first and breaks ties in the wrong direction if you negate the whole tuple vianlargestwithout negatingbalanceselectively. - Incrementing
next_transfer_idbeforeschedulevalidation finishes: invalidschedulecalls must returnNonewithout creating gaps in transfer IDs (1, 2, 3, ...). - Deleting from
due_heapwithlist.remove+heapq.heapify: turnscancelfromO(1)intoO(S). Markingstatus = "cancelled"and skipping on pop is both simpler and faster.
Alternative approaches
- Single central dispatcher for
_catch_up: Sinceworkspace_credit_systemalready funnels all calls through one loop, you could callsystem.catch_up(args[0])once at the top of that loop instead of inside each method. Callingself._catch_up(timestamp)inside each public method is safer in multi-level OOP assessments where automated tests invoke methods onWorkspaceCreditsdirectly. - Eager credit reservation (escrow at
scheduletime): Some banking variants deductamountimmediately whenscheduleis called and refund it oncancel. That guarantees due transfers never fail for insufficient funds, but prevents scheduling transfers against incoming future funds (which Sample/test cases here allow). Always clarify which policy applies in an interview.
Follow-up questions
- Suppose we add an operation that consolidates two workspaces into one—how should pending scheduled transfers involving the absorbed workspace be updated? In
consolidate(ts, survivor, absorbed), first call_catch_up(ts), verify both IDs exist and differ, addbalances[absorbed]intobalances[survivor], and deleteabsorbedfrombalances. For still-pending scheduled transfers referencingabsorbed, rewriteabsorbed -> Xintosurvivor -> X(handing cancellation rights tosurvivor), rewriteX -> absorbedintoX -> survivor, and mark any pending transfer directly betweenabsorbedandsurvivoras"cancelled"since it has collapsed into a self-transfer. Keeping an auxiliary indexpending_by_workspace[id] -> set of transfer_idslets consolidation touch only affected transfers instead of scanning allSrecords. - How could you support historical point-in-time balance lookups for any past timestamp, and what extra state must be logged from day one? From the moment each workspace is created, keep an append-only history list (a log where new snapshots are only ever appended, never overwritten)
history[id] = [(create_ts, 0), ...]recording(event_time, new_balance)on every balance mutation—crucially stamping due scheduled transfers with theirexecute_attimestamp rather than the later caller'stimestamp. Because event timestamps never decrease, each list stays sorted automatically, allowing binary search (bisect_right— repeatedly halving the search interval) to locate the latest balance at or beforetinO(log H)time forHupdates on that workspace (Noneift < create_ts). Recording must begin on the very first operation because keeping only live balances destroys prior history. - How would you optimize ranking queries when read traffic vastly outnumbers balance mutations? The simplest upgrade pairs a cached ranked list of IDs with a boolean
dirtyflag: setdirty = Trueonly whencreate,add,transfer, or a due transfer inside_catch_upactually changes a balance, re-sort inO(W log W)on the firsttop_kafter a mutation, and answer subsequent reads inO(k)viacached[:k]. If both mutations andtop_kqueries run at high volume over hugeW, store(-balance, workspace_id)tuples in a balanced binary search tree (a sorted tree container such assortedcontainers.SortedListsupportingO(log W)insertions and removals) so each balance change updates at most two entries inO(log W)time whiletop_kslices the leadingkkeys inO(k)time. - Which invariants fail if requests arrive with non-monotonic timestamps, and what design changes can accommodate late events? Our
_catch_uploop relies on monotonic time: once a transfer due att = 20mutatesbalances, a late-arrivingtop_k(15, 2)orcancel(15, "core", 1)would wrongly observe post-20state that did not exist att = 15. Depending on system requirements, you can reject calls belowlatest_timestamp, buffer incoming requests briefly behind a watermark (a lower-bound timestamp below which late arrivals are no longer accepted), or store an append-only event log of raw commands so an out-of-order request inserts at its true timestamp and replays the affected suffix from a periodic checkpoint.
Follow-up questions
- Suppose we add an operation that consolidates two workspaces into one—how should pending scheduled transfers involving the absorbed workspace be updated?
- How could you support historical point-in-time balance lookups for any past timestamp, and what extra state must be logged from day one?
- How would you optimize ranking queries when read traffic vastly outnumbers balance mutations?
- Which invariants fail if requests arrive with non-monotonic timestamps, and what design changes can accommodate late events?
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
- Workspace Credit Ledger with Delayed Rebates and Merges
More Airbnb interview questions
- Stateful Credit Ledger with Delayed Transfers and Account Merges 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