Implement a Timed Workspace Credit System
Data Structure DesignAuto-graded · 22 test casesLast updated
Process a sequence of timestamped operations managing workspace balances, immediate transfers, scheduled/cancelled future transfers, and ranked queries.
Design an in-memory credit tracking system that processes a series of timestamped commands. The system manages workspace accounts, supports instant and scheduled transfers, allows cancellation of scheduled transfers, and can query the top workspaces by balance.
Every command in operations has a corresponding argument list in arguments. The first entry of every argument list is an integer timestamp. Timestamps across calls are non-decreasing.
Before executing any operation at a given timestamp, all pending scheduled transfers due at or before timestamp (execute_at <= timestamp) must take effect in the chronological order of their scheduled execution time. If multiple transfers are scheduled for the exact same execute_at time, process them in the order they were scheduled (earlier schedule operations run first).
Command Specifications
-
"create":[timestamp, workspace_id]- Creates a workspace with initial balance
0. - Returns
Trueif created successfully. - Returns
Falseifworkspace_idalready exists.
- Creates a workspace with initial balance
-
"add":[timestamp, workspace_id, amount]- Increases the balance of
workspace_idbyamount. - Returns
Trueif successful. - Returns
Falseifworkspace_iddoes not exist oramount <= 0.
- Increases the balance of
-
"transfer":[timestamp, source, destination, amount]- Instantly transfers
amountcredits fromsourcetodestination. - Returns
Trueif successful. - Returns
Falseif:sourceordestinationdoes not exist,source == destination,amount <= 0, orsourcehas strictly less thanamountcredit.
- Instantly transfers
-
"top_k":[timestamp, k]- Returns a list of up to
kworkspace IDs sorted descending by current balance. - Tie-breaking: If two workspaces have equal balances, order them lexicographically ascending by
workspace_id. - If
k <= 0, return[]. Ifkexceeds the total number of existing workspaces, return all workspaces in sorted order.
- Returns a list of up to
-
"schedule":[timestamp, source, destination, amount, execute_at]- Schedules a future transfer of
amountfromsourcetodestinationto execute atexecute_at. - Returns an integer
transfer_id(1-indexed counter starting from 1 for the first valid scheduled transfer) if successfully scheduled. - Returns
Noneif:sourceordestinationdoes not exist,source == destination,amount <= 0, orexecute_at <= timestamp.
- Note: Credit sufficiency is not checked when scheduling; it is evaluated when the transfer comes due.
- Schedules a future transfer of
-
"cancel":[timestamp, workspace_id, transfer_id]- Cancels a pending scheduled transfer identified by
transfer_id. workspace_idmust match thesourceworkspace of the scheduled transfer.- Returns
Trueif successfully cancelled. - Returns
Falseiftransfer_iddoes not exist, has already been processed or cancelled, or ifworkspace_idis not the source workspace.
- Cancels a pending scheduled transfer identified by
Processing Due Scheduled Transfers
When a scheduled transfer becomes due (execute_at <= current_timestamp):
- If it has been cancelled or previously executed, ignore it.
- If
sourceordestinationno longer exists,source == destination,amount <= 0, orsourcecurrently has fewer thanamountcredits, the transfer fails silently (balances remain unchanged). - Otherwise, deduct
amountfromsourceand addamounttodestination.
Constraints
1 <= len(operations) == len(arguments) <= 10^4timestampvalues are non-decreasing across consecutive operations.- Workspace IDs are strings.
- Credit amounts and
kare integers. execute_atis an integer timestamp.
Examples
Example 1
Input: workspace_credit_system(['create', 'add', 'add', 'transfer', 'top_k'], [[1, 'a'], [2, 'a', 100], [3, 'b', 50], [4, 'a', 'b', 30], [5, 2]])
Output: [True, True, False, False, ['a']]
Example 2
Input: workspace_credit_system(['create', 'create', 'add', 'schedule', 'top_k', 'top_k'], [[1, 'a'], [2, 'b'], [3, 'a', 100], [4, 'a', 'b', 40, 10], [5, 2], [10, 2]])
Output: [True, True, True, 1, ['a', 'b'], ['a', 'b']]
Example 3
Input: workspace_credit_system(['create', 'create', 'add', 'schedule', 'cancel', 'top_k'], [[1, 'a'], [2, 'b'], [3, 'a', 100], [4, 'a', 'b', 20, 20], [5, 'a', 1], [20, 2]])
Output: [True, True, True, 1, True, ['a', 'b']]
Hints
Hint 1
Before processing any command at the current timestamp, drain all pending transfers from a min-heap where execute_at <= current_timestamp.
Hint 2
Use a unique sequential counter to break ties in the min-heap for scheduled transfers with identical execute_at timestamps.
Hint 3
Maintain a hash map of active pending transfers so that cancellations can mark transfers as invalid in O(1) time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks us to maintain dynamic balances for a set of workspaces across sequence of operations with non-decreasing timestamps. The key challenge lies in managing scheduled future transfers and ensuring they execute at the right time before any subsequent read/write operation.
-
State Tracking:
balances: A dictionary mappingworkspace_id -> balance.heap: A min-heap storing pending transfers ordered by(execute_at, sequence_number, transfer_id, source, destination, amount). Using asequence_numberensures that ties inexecute_atare broken by scheduling order.pending: A dictionary mappingtransfer_id -> detailsto facilitate lazy deletion or validation during cancellation.
-
Pre-operation Catch-up (
apply_due):- Before evaluating any operation at
timestamp, pop all items fromheapwhereexecute_at <= timestamp. - Check if the transfer is still valid in
pending. If it was cancelled, skip it. - Validate if
sourceanddestinationexist and ifsourcehas enough credit. If valid, update the balances; otherwise, skip execution without modifying balances.
- Before evaluating any operation at
-
Operation Handling:
"create": Add tobalanceswith0balance if not present."add": Increase balance if workspace exists andamount > 0."transfer": Validate accounts and balance, then instantly move credits."top_k": Sort workspace keys by(-balance, workspace_id)and take the firstkelements."schedule": Validate inputs and return a incrementaltransfer_id. Push toheapand record inpending."cancel": Removetransfer_idfrompendingifworkspace_idmatches the source.
Complexity Analysis
-
Time Complexity:
- Each
scheduleand pop operation on the min-heap takes $O(\log N)$ time, where $N$ is the number of scheduled transfers. - Sorting for
top_ktakes $O(M \log M)$, where $M$ is the number of workspaces. - Overall time complexity for $Q$ operations is $O(Q \cdot (\log N + M \log M))$.
- Each
-
Space Complexity: $O(M + N)$ auxiliary space to store workspace balances, the priority queue, and pending transfers.
Python Reference Solution
import heapq
from typing import List
def workspace_credit_system(operations: List[str], arguments: List[List]) -> List:
balances = {}
pending = {}
heap = []
results = []
next_transfer_id = 1
sequence = 0
def apply_due(timestamp):
while heap and heap[0][0] <= timestamp:
due, order, transfer_id, source, destination, amount = heapq.heappop(heap)
transfer = pending.pop(transfer_id, None)
if transfer is None:
continue
if source in balances and destination in balances:
if source != destination and balances[source] >= amount:
balances[source] -= amount
balances[destination] += amount
for operation, args in zip(operations, arguments):
timestamp = args[0]
apply_due(timestamp)
if operation == "create":
workspace_id = args[1]
if workspace_id in balances:
results.append(False)
else:
balances[workspace_id] = 0
results.append(True)
elif operation == "add":
workspace_id, amount = args[1], args[2]
if workspace_id not in balances or amount <= 0:
results.append(False)
else:
balances[workspace_id] += amount
results.append(True)
elif operation == "transfer":
source, destination, amount = args[1], args[2], args[3]
if (source not in balances or destination not in balances or
source == destination or amount <= 0 or
balances[source] < amount):
results.append(False)
else:
balances[source] -= amount
balances[destination] += amount
results.append(True)
elif operation == "top_k":
k = args[1]
if k <= 0:
results.append([])
else:
ranked = sorted(balances.keys(), key=lambda w: (-balances[w], w))
results.append(ranked[:k])
elif operation == "schedule":
source, destination, amount, execute_at = args[1], args[2], args[3], args[4]
if (source not in balances or destination not in balances or
source == destination or amount <= 0 or execute_at <= timestamp):
results.append(None)
else:
transfer_id = next_transfer_id
next_transfer_id += 1
sequence += 1
pending[transfer_id] = (execute_at, sequence, source, destination, amount)
heapq.heappush(heap, (execute_at, sequence, transfer_id, source, destination, amount))
results.append(transfer_id)
elif operation == "cancel":
workspace_id, transfer_id = args[1], args[2]
transfer = pending.get(transfer_id)
if transfer is None or transfer[2] != workspace_id:
results.append(False)
else:
del pending[transfer_id]
results.append(True)
else:
results.append(False)
return results