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, amount moves from sender to receiver, and both balance changes are recorded at due_time (not the outer caller's timestamp).

Operations

  1. Account Creation & Deposits:

    • create_workspace(timestamp: int, workspace_id: str) -> bool: creates an active workspace with initial balance 0 and returns True, or returns False if workspace_id is 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]: adds amount to workspace_id and returns its updated balance, or returns None if workspace_id is not currently active.
  2. Immediate Transfers & Leaderboard:

    • transfer(timestamp: int, source_id: str, target_id: str, amount: int) -> Optional[int]: atomically moves amount from source_id to target_id at timestamp and returns source_id's resulting balance. Returns None without modifying any state if either workspace is not active, source_id == target_id, or source_id's balance is less than amount.
    • top_k(timestamp: int, k: int) -> List[Tuple[str, int]]: returns up to k (workspace_id, balance) pairs among currently active workspaces, sorted by balance descending and breaking ties by workspace_id ascending. Returns all active workspaces if fewer than k exist, or [] if k <= 0.
  3. Delayed Transfers & Cancellation:

    • schedule_transfer(timestamp: int, source_id: str, target_id: str, amount: int, delay: int) -> Optional[str]: registers a pending transfer with due_time = timestamp + delay and returns sequential identifiers "transfer1", "transfer2", "transfer3", ... across accepted calls. Returns None (without consuming a sequence number) if either workspace is not active or source_id == target_id.
    • cancel_transfer(timestamp: int, transfer_id: str) -> bool: cancels transfer_id and returns True if it exists and remains pending after processing transfers due at or before timestamp. Returns False if transfer_id is unknown or has already executed, failed, or been canceled (so canceling at timestamp >= due_time always returns False).
  4. Account Consolidation & Historical Point-in-Time Queries:

    • merge_workspaces(timestamp: int, target_id: str, source_id: str) -> bool: if both workspaces are active and target_id != source_id, cancels every still-pending scheduled transfer touching source_id (whether as sender or receiver), adds source_id's entire current balance to target_id at timestamp (without copying source_id's prior history into target_id), retires source_id starting at timestamp, and returns True; otherwise returns False.
    • get_balance(timestamp: int, workspace_id: str, time_at: int) -> Optional[int]: returns the balance of workspace_id after all updates with effective time <= time_at, or None if time_at > timestamp or no workspace with workspace_id was active at time_at. A workspace created at t_start and merged away at t_merge is active on the half-open interval [t_start, t_merge), so its pre-merge balances remain queryable for t_start <= time_at < t_merge, while time_at == t_merge returns None.

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, and target_id are non-empty strings.
  • amount >= 1 and delay >= 1 are positive integers; k and time_at are integers with time_at <= timestamp on valid historical queries.
  • Account balances are always non-negative integers.

Step-by-step walkthrough

  1. 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) True False if id is currently active
    add_credit(t, id, amount) new integer balance None if id is not active
    transfer(t, src, dst, amount) src's new balance None (no balance changes)
    top_k(t, k) [(id, balance), ...] [] if k <= 0 or no workspaces exist
    schedule_transfer(t, src, dst, amount, delay) "transfer1", "transfer2", ... None (does not consume an ID number)
    cancel_transfer(t, transfer_id) True False
    merge_workspaces(t, dst, src) True False
    get_balance(t, id, time_at) integer balance at time_at None if id did not exist at time_at

    Nothing 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 whose due <= t, stamping each executed transfer's balance change with its due time (not t):

    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 to timestamp.

  2. 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 own Workspace object and route every balance mutation through one helper method, change(timestamp, delta).

    Why build this up front? Because timestamps never move backward. Every time change updates self.balance, it appends (timestamp, self.balance) to two parallel arrays (self.times and self.balances). Point-in-time historical queries can then read those sorted arrays directly without replaying transactions.

    What if "ads" is merged away at t = 15 and created again at t = 17 (as in Example 2)? Those are two separate lifetimes of "ads". WorkspaceManager maintains: - self.workspaces: only the currently active Workspace for each ID, for O(1) lookup. - self.lives: a chronological list of every Workspace lifetime 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)
    
  3. Implement atomic instant transfers and top-k ranking

    An immediate transfer updates two accounts. Subtracting from source before confirming target exists would leave credits missing when target_id is invalid. Validate every precondition first (both accounts active, source_id != target_id, and source.balance >= amount), and only then call change on both endpoints. Notice the inclusive boundary: amount == source.balance succeeds and leaves 0.

    For top_k, we want highest balances first, breaking ties by workspace_id ascending ("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 result
    
  4. Schedule 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 where queue[0] is always the minimum tuple and push/pop each take O(log q) time.

    We push (due_time, creation_number, transfer_id) onto the heap: 1. due_time runs earliest-due transfers first. 2. creation_number (an integer 1, 2, ..., 10, ...) breaks ties in creation order. Never break ties using the string transfer_id directly—lexicographically, "transfer10" < "transfer2" because '1' < '2', which would execute the 10th transfer ahead of the 2nd!

    When cancel_transfer is called, deleting from the middle of a binary heap would cost O(q). Instead, use lazy deletion: mark transfer.status = "canceled" in O(1) time and leave the tuple inside the heap. When _catch_up eventually pops that entry, it sees transfer.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 Workspace also keeps self.pending (the set of pending transfer_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 True
    
  5. Merge accounts in the exact required order

    When merge_workspaces(timestamp, target_id, source_id) consolidates source into target, the step order matters: 1. Catch up to timestamp first: any scheduled transfer with due <= timestamp executes normally prior to the merge. 2. Validate: both target and source must be active and distinct (target_id != source_id). 3. Cancel remaining pending transfers touching source: iterate over list(source.pending) (a snapshot copy, because _cancel mutates source.pending during iteration!) and cancel each one. 4. Credit target: add source.balance to target at timestamp via target.change(timestamp, source.balance). 5. Retire source: set source.removed_at = timestamp and delete source_id from self.workspaces, while keeping source inside self.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 True
    
  6. Answer historical balances with binary search

    Why is workspace.times guaranteed to remain sorted even when delayed transfers record updates at due? Suppose the prior call was at t = 12, a scheduled transfer is due at 16, and the next call arrives at t = 18. Every entry recorded so far has timestamp <= 12; _catch_up(18) records the due transfer at 16 (>= 12); then the call at 18 records any new change at 18 (>= 16). Timestamps in self.times never decrease!

    To evaluate balance_at(time_at) on one Workspace lifetime: 1. Check whether time_at lies in [created_at, removed_at): if time_at < created_at, or removed_at is not None and time_at >= removed_at, return None. 2. Locate the last entry with timestamp <= time_at using bisect_right(self.times, time_at) - 1. Using bisect_right (rather than bisect_left) steps past all updates stamped at time_at, which handles cases where a due transfer and a direct deposit share the exact same timestamp t = 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] = 9
    
    from 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 None
    
  7. Walk through Example 1 end to end

    Tracing Example 1's 12 calls shows how _catch_up, times/balances, and removed_at interact:

    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)]
    
  8. 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 to times and balances.
  • top_k: O(n log n) time and O(n) temporary space beyond _catch_up, because we build one (-balance, id) tuple for each of the n active accounts and sort them.
  • schedule_transfer and cancel_transfer: schedule_transfer takes O(log q) time to push one tuple onto the min-heap plus O(1) dictionary and set insertions. cancel_transfer takes O(1) time beyond _catch_up because it flips transfer.status and discards the ID from two pending sets without scanning the heap.
  • _catch_up (amortized across calls): Each scheduled transfer is pushed once and popped at most once, so across S total scheduled transfers the cumulative heap cost is O(S log S), or O(log q) amortized per scheduled transfer.
  • merge_workspaces: O(p) time beyond _catch_up, because we loop directly over the p transfer IDs in source.pending rather 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 takes O(1), and because lifetimes of the same ID never overlap in time, at most one lifetime runs bisect_right in O(log h) steps.
  • Space: O(C + S) total memory, where C is the total number of balance-changing events and S is the total number of scheduled transfers stored in self.transfers.

Edge cases

  • Duplicate vs. recreated workspace IDs: Calling create_workspace on a currently active ID returns False, whereas calling it on an ID retired by a prior merge starts a fresh Workspace lifetime at balance 0 with independent history.
  • Transfer boundaries: Self-transfers (source_id == target_id), unknown IDs, and amount > source.balance return None with zero side effects; amount == source.balance succeeds and leaves 0.
  • top_k bounds and ties: Tied balances break alphabetically by workspace_id ascending; k exceeding the active count returns all active workspaces, and k <= 0 returns [].
  • Cancel at the exact due time: Because _catch_up(timestamp) executes transfers with due <= timestamp first, cancel_transfer(12, "transfer1") for a transfer due at 12 arrives after execution and returns False.
  • 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 = 7 executes right before add_credit(7, ...), times contains two 7s; bisect_right(times, 7) - 1 selects the final entry at 7 so get_balance(..., time_at=7) reflects both changes.
  • Existence boundaries around a merge: An account created at 4 and merged away at 20 covers the half-open interval [4, 20) (an interval including its start point 4 and excluding its end point 20), so get_balance returns 0 at 4 and None at 20.

Common mistakes

  • Skipping _catch_up on read-only or failing calls: Even when cancel_transfer or transfer fails, or top_k only reads balances, pending transfers due at or before timestamp must execute first.
  • Mutating the sender before validating the receiver: Subtracting from source before checking target leaves a partial debit when target is invalid; always enforce an all-or-nothing (atomic) update (an operation that either applies every part or changes nothing).
  • Recording scheduled transfers at timestamp instead of due: Stamping a transfer due at 16 with the caller's timestamp = 18 corrupts get_balance queries for time_at = 16 and time_at = 17.
  • Breaking heap ties with the string ID: Comparing "transfer10" and "transfer2" lexicographically puts "transfer10" first because '1' < '2'; always include the integer self.transfer_count in the heap tuple.
  • Mutating source.pending while iterating over it: _cancel removes transfer IDs from source.pending, so looping over source.pending directly raises RuntimeError: Set changed size during iteration; iterate over list(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 to time_at on each get_balance call. Simple to write, but get_balance degrades to O(total events) per query instead of O(log h).
  • Linear scan of scheduled transfers on _catch_up: Scanning a list of all scheduled transfers for due <= timestamp works on tiny inputs, but costs O(S) on every method call rather than O(log q) per due transfer with a min-heap.

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? 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 repeated top_k calls by slicing cached[:k] in O(k) time. When both reads and writes are frequent, maintain active accounts inside an order-statistic tree or balanced BST (such as sortedcontainers.SortedList) keyed by (-balance, id): each balance update removes the old key and inserts the new key in O(log n) time, while top_k iterates the first k entries in O(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-account pending: Set[str] index on every Workspace instance: insert transfer_id into both source.pending and target.pending during schedule_transfer, and discard it from both endpoints whenever a transfer executes, fails, or is canceled. During merge_workspaces, iterate over list(source.pending) in O(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_up uses <=, same-time updates append in arrival order, and bisect_right selects the final balance at time_at. Out-of-order (decreasing) timestamps violate three invariants: times is no longer sorted, a delayed transfer at t = 12 may have already failed for insufficient funds before an earlier deposit at t = 9 arrives, and a cancel at t = 11 could arrive after execution at t = 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 WorkspaceManager so 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 instant transfer calls after catching up, acquire per-account locks in canonical ID order (min(source_id, target_id) before max(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, and top_k under a reader-writer lock or single-writer command queue.

Follow-up questions

Similar questions

More Airbnb interview questions

All 112 Airbnb questions →