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 0 credits and returns True.
    • If workspace_id already exists, leaves state unchanged and returns False.
  • "add" — [timestamp, workspace_id, amount]
    • Adds amount credits to workspace_id and returns True.
    • If workspace_id does not exist or amount <= 0, leaves state unchanged and returns False.
  • "transfer" — [timestamp, source, target, amount]
    • Atomically moves amount credits from source to target and returns True.
    • Returns False without modifying any balance if either workspace ID is unknown, source == target, amount <= 0, or source currently has fewer than amount credits.
  • "top_k" — [timestamp, k]
    • Returns a List[str] of up to k workspace IDs sorted by current credit balance descending, breaking ties by workspace_id in ascending lexicographical order.
    • Returns [] when k <= 0 or zero workspaces exist; returns all existing workspace IDs in ranked order when k exceeds the workspace count.
  • "schedule" — [timestamp, source, target, amount, execute_at]
    • Registers a future transfer of amount credits from source to target scheduled for execute_at.
    • Returns None (without consuming a transfer ID) if either workspace ID is unknown, source == target, amount <= 0, or execute_at <= timestamp. Current credit in source is not checked at scheduling time.
    • Each valid "schedule" call assigns and returns the next 1-based sequential integer transfer_id (1, 2, 3, ...).
    • When execute_at arrives during catch-up, amount moves from source to target if source holds at least amount credits at that moment; otherwise no credits move and the transfer permanently fails (it is never retried and can no longer be cancelled).
  • "cancel" — [timestamp, workspace_id, transfer_id]
    • Cancels transfer_id and returns True if and only if workspace_id exists, transfer_id exists, workspace_id is the transfer's source, and the transfer remains pending after catching up to timestamp. Otherwise returns False.

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^5
  • 0 <= 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

  1. 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 integer timestamp:

    Operation Arguments Return value
    create [ts, workspace_id] True if created at balance 0; False if ID already exists
    add [ts, workspace_id, amount] True if added; False if ID is unknown or amount <= 0
    transfer [ts, source, target, amount] True if moved; False on invalid IDs, self-transfer, amount <= 0, or insufficient credit
    top_k [ts, k] Up to k workspace IDs ordered by highest balance, ties broken by ID ascending
    schedule [ts, source, target, amount, execute_at] Serial integer ID 1, 2, 3, ... if valid and execute_at > ts, else None
    cancel [ts, workspace_id, transfer_id] True if workspace_id == source and the transfer is still pending at ts, else False

    Key behavioral contracts matching all samples:

    • No negative balances and no partial writes: any rejected call leaves all state untouched (and a rejected schedule does not consume a transfer_id).
    • Due transfers run before the call at ts: every operation — including read-only top_k — first applies all pending transfers with execute_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_at arrives, that transfer is marked "failed" and never retried.
  2. Choose the core data structures

    Parts 1 and 2 only need a dictionary balances mapping workspace_id -> credit. Part 3 introduces pending future work: scanning a plain list of all S scheduled transfers before every call would cost O(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 index 0 is 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 in due_heap solves two problems at once:

    1. due_heap[0] tells us in O(1) time whether anything has come due (execute_at <= timestamp).
    2. If two transfers share the exact same execute_at, Python compares the second tuple element (transfer_id), automatically running the earlier-scheduled transfer first!
  3. Part 1 · Validate everything before changing any balance

    A transfer touches two workspaces and can fail for five reasons: unknown source, unknown target, source == target, amount <= 0, or balances[source] < amount. Subtracting from source before checking target would corrupt source's balance whenever target is invalid.

    Splitting validation into _valid_pair (structural checks shared with schedule) 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 2 due_heap is empty so _catch_up returns immediately; in Part 3 every method automatically sees up-to-date balances!

  4. Part 2 · Rank workspaces with a negated-balance tuple key

    top_k wants highest balance first, and alphabetical workspace_id ascending on ties ("eng" before "ops" when both have 40 credits).

    Python compares tuples left to right in ascending order. By pairing -balance with workspace_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 best k tuples in O(W log k) time for W workspaces (and gracefully returns all W workspaces when k > W), while if k <= 0: return [] handles zero or negative k.

        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
    
  5. Part 3 · Schedule transfers and cancel with lazy deletion

    When schedule is called at timestamp:

    1. Catch up due transfers up to timestamp.
    2. Verify _valid_pair(source, target, amount) and execute_at > timestamp (must be strictly in the future). Return None immediately if anything is invalid so next_transfer_id is not wasted.
    3. Store the transfer dictionary with "status": "pending" and push (execute_at, transfer_id) onto due_heap.

    When cancel is called, removing (execute_at, transfer_id) directly from the middle of due_heap would require an O(S) linear scan plus re-heapifying. Instead, we use lazy deletion: after catching up to timestamp, we check that the transfer is still "pending" and belongs to workspace_id, and simply flip transfer["status"] = "cancelled" in O(1) time. When (execute_at, transfer_id) eventually reaches the top of due_heap, _catch_up sees "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
    
  6. Catch up due transfers before every read and write

    _catch_up(timestamp) pops from due_heap while the earliest due time satisfies execute_at <= timestamp:

    • If status != "pending", it was cancelled earlier — continue.
    • Otherwise try _move(source, target, amount). If source has enough credit right now, the balances update immediately (so another transfer due at the same or a later timestamp sees the updated balances!) and status becomes "done". Otherwise status becomes "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_system instantiates WorkspaceCredits() once and dispatches each (op, args) pair in order.

  7. Trace Example 2 and competing scheduled transfers

    First see how Example 2 shifts rankings right at t = 15: "core" starts at 90 credits, schedules 60 to "data" for execute_at = 15 (transfer_id = 1), still leads ["core", "data"] at t = 12, and then _catch_up(15) moves the 60 credits before top_k(15, 2) runs, flipping the order to ["data", "core"].

    Now trace a fuller scenario where two scheduled transfers compete for "core"'s 50 credits 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 at t = 15) ran before #1 (due at t = 20) and took "core"'s 50 credits, causing #1 to fail cleanly at t = 20.

  8. 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) onto due_heap (excluding _catch_up).
  • top_k: O(W log k) time when k < W because heapq.nsmallest scans all W workspace keys while maintaining a bounded heap of size k (or O(W log W) when k >= W, where Python sorts the W keys directly).
  • _catch_up across all n calls: O(S log S) total time, or O(log S) amortized time per scheduled transfer (meaning that although one single call might pop many due transfers at once, each of the S transfers is pushed onto due_heap once and popped at most once across the entire run).
  • Space: O(W + S). balances stores W workspaces, ranking_keys temporarily holds W tuples during top_k, and transfers plus due_heap store one entry per scheduled transfer (S entries total).

Edge cases

  • Unknown or duplicate workspace IDs: creating an existing ID or referencing a missing ID in any operation returns False (None for schedule) without mutating state.
  • Self-transfers and non-positive amounts: source == target and amount <= 0 are rejected in both transfer and schedule; add also rejects amount <= 0.
  • Exact-balance transfer: transferring amount == balances[source] succeeds and leaves 0; requesting 1 more credit fails cleanly.
  • top_k boundary sizes: k <= 0 or zero created workspaces returns []; k > W returns all W workspace IDs in ranked order.
  • Balance ties: broken deterministically by workspace_id in ascending alphabetical order (including newly created workspaces tied at 0).
  • Boundary timestamps (execute_at == timestamp): in schedule, execute_at <= timestamp is rejected as non-future; in _catch_up, execute_at <= timestamp runs before the operation at timestamp, so calling cancel at t == execute_at returns False because the transfer has already run.
  • Same-timestamp due transfers: two transfers due at the same execute_at execute in scheduling order (transfer_id ascending); 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 source before validating target: subtracting balances[source] -= amount before confirming target in self.balances corrupts source when target is missing. Check every precondition first.
  • Skipping _catch_up in top_k: read operations must also advance pending transfers up to timestamp, or top_k will compute rankings on outdated balances.
  • Using < instead of <= in _catch_up: writing due_heap[0][0] < timestamp delays transfers due at timestamp until after the call at timestamp.
  • Pushing (balance, workspace_id) into heapq: Python's heapq is a min-heap, so un-negated balance returns the poorest workspaces first and breaks ties in the wrong direction if you negate the whole tuple via nlargest without negating balance selectively.
  • Incrementing next_transfer_id before schedule validation finishes: invalid schedule calls must return None without creating gaps in transfer IDs (1, 2, 3, ...).
  • Deleting from due_heap with list.remove + heapq.heapify: turns cancel from O(1) into O(S). Marking status = "cancelled" and skipping on pop is both simpler and faster.

Alternative approaches

  • Single central dispatcher for _catch_up: Since workspace_credit_system already funnels all calls through one loop, you could call system.catch_up(args[0]) once at the top of that loop instead of inside each method. Calling self._catch_up(timestamp) inside each public method is safer in multi-level OOP assessments where automated tests invoke methods on WorkspaceCredits directly.
  • Eager credit reservation (escrow at schedule time): Some banking variants deduct amount immediately when schedule is called and refund it on cancel. 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, add balances[absorbed] into balances[survivor], and delete absorbed from balances. For still-pending scheduled transfers referencing absorbed, rewrite absorbed -> X into survivor -> X (handing cancellation rights to survivor), rewrite X -> absorbed into X -> survivor, and mark any pending transfer directly between absorbed and survivor as "cancelled" since it has collapsed into a self-transfer. Keeping an auxiliary index pending_by_workspace[id] -> set of transfer_ids lets consolidation touch only affected transfers instead of scanning all S records.
  • 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 their execute_at timestamp rather than the later caller's timestamp. 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 before t in O(log H) time for H updates on that workspace (None if t < 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 dirty flag: set dirty = True only when create, add, transfer, or a due transfer inside _catch_up actually changes a balance, re-sort in O(W log W) on the first top_k after a mutation, and answer subsequent reads in O(k) via cached[:k]. If both mutations and top_k queries run at high volume over huge W, store (-balance, workspace_id) tuples in a balanced binary search tree (a sorted tree container such as sortedcontainers.SortedList supporting O(log W) insertions and removals) so each balance change updates at most two entries in O(log W) time while top_k slices the leading k keys in O(k) time.
  • Which invariants fail if requests arrive with non-monotonic timestamps, and what design changes can accommodate late events? Our _catch_up loop relies on monotonic time: once a transfer due at t = 20 mutates balances, a late-arriving top_k(15, 2) or cancel(15, "core", 1) would wrongly observe post-20 state that did not exist at t = 15. Depending on system requirements, you can reject calls below latest_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

Similar questions

More Airbnb interview questions

All 112 Airbnb questions →