KatInterview

Building a Multi-Level Credit Ledger with Timed Transfers and Merges

Data Structure DesignModel answer
MediumModel answerData Structure Designclass-designheapbinary-search

Last updated

Build an in-memory ledger of credit-holding workspaces in four stages: transfers with a top-k ranking, timed transfers with cancellation, workspace merges, and point-in-time balance lookups.

Implement a class WorkspaceManager that tracks workspaces holding credit, like bank accounts that can pay one another. The work comes in four levels. Each level adds methods, and everything from earlier levels must keep working. Exact return values matter, so treat them as a spec that automated tests would check.

Ground rules

  • Every method takes an integer timestamp as its first argument. Timestamps strictly increase from call to call.
  • Workspace ids are non-empty strings. Every amount and delay is a positive integer.
  • Balances are integers and never drop below zero.
  • Invalid requests (such as an unknown id) return the failure value listed for the method. They never raise.

Policies fixed for this version

  • Failures return a sentinel (False or None) rather than raising.
  • top_k breaks ties by workspace id, ascending.
  • A scheduled transfer checks the sender's balance only when it executes. Nothing is set aside when it is scheduled.
  • After a workspace is merged away, its id may be created again as a new workspace with its own history.
  • After a merge, the target's history shows the absorbed credit only from the merge time onward.

Level 1: Creating workspaces and adding credit

  • create_workspace(timestamp, workspace_id) -> bool: create a workspace with 0 credit. Return False and change nothing if the id exists.
  • add_credit(timestamp, workspace_id, amount) -> int | None: add credit and return the new balance, or None if the workspace does not exist.

Level 2: Immediate transfers and ranking

  • transfer(timestamp, source_id, target_id, amount) -> int | None: move credit now and return the source's new balance. Return None and change nothing if either workspace is missing, the two ids are equal, or the source holds less than amount.
  • top_k(timestamp, k) -> list[tuple[str, int]]: return (workspace_id, balance) for the k workspaces with the most credit, highest first, ties by id ascending. If fewer than k workspaces exist, return all of them.

Level 3: Scheduled transfers

  • schedule_transfer(timestamp, source_id, target_id, amount, delay) -> str | None: register a transfer due at timestamp + delay. Return ids "transfer1", "transfer2", ... in creation order. Return None if either workspace is missing or the ids are equal.
  • cancel_transfer(timestamp, transfer_id) -> bool: cancel a transfer that is still pending and return True. Return False if the id is unknown or the transfer has already executed, failed or been canceled.

Rules:

  • Before any call at time t does its own work, every pending transfer due at or before t executes, ordered by due time and then by creation order. A cancel arriving at or after the due time is too late.
  • If the sender cannot cover the amount at execution time, the transfer fails and changes nothing.

Level 4: Merging and historical balances

  • merge_workspaces(timestamp, target_id, source_id) -> bool: the target receives all of the source's credit, the source is deleted, and every still-pending scheduled transfer involving the source (as sender or receiver) is canceled. Return False and change nothing if either workspace is missing or the ids are equal. Transfers due at or before timestamp run first, so only those still pending afterward are canceled.
  • get_balance(timestamp, workspace_id, time_at) -> int | None, with time_at <= timestamp: return the balance at time_at, after all changes made at times up to and including time_at. Return None if no workspace with that id existed at time_at. An executed scheduled transfer counts as happening at its due time. A merged-away workspace stops existing at the merge time, but its earlier history can still be queried.

Example

CallReturnsNote
create_workspace(1, "A")True
create_workspace(2, "B")True
add_credit(3, "A", 100)100
transfer(4, "A", "B", 30)70A=70, B=30
schedule_transfer(5, "B", "A", 20, 5)"transfer1"due at 10
top_k(6, 2)[("A", 70), ("B", 30)]
get_balance(11, "A", 9)70transfer1 runs first, at time 10
get_balance(12, "A", 10)90
merge_workspaces(13, "A", "B")TrueA = 90 + 10
get_balance(14, "B", 12)10
get_balance(15, "B", 13)NoneB merged away at 13
top_k(16, 5)[("A", 100)]

What to deliver

Explain your design and the data structures behind each level, state the complexity of each operation, give working code, and point out the edge cases you handle.

Hints

Hint 1

Give every public method the same first step: run all pending transfers due at or before the call's timestamp. That one rule makes 'cancel too late' and 'merge only cancels what is still pending' follow naturally.

Hint 2

Keep pending transfers in a min-heap keyed by (due_time, creation_sequence). Cancel by marking the record, and let the catch-up loop skip anything that is no longer pending.

Hint 3

For history, store sorted (time, balance) change points per workspace and binary search them. Keep one record per incarnation of an id, with created and deleted times, so a re-created id never mixes with the old one.