Credit Ledger Simulator with Merges and Delayed Rewards
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a timestamped ledger with deposits, transfers, spends with delayed cashback, account merges and spend rankings, using union-find and a min-heap.
Credit Ledger Simulator
You are building the engine behind a shared credit ledger for team workspaces. Each workspace is identified by a string ID and holds a non-negative integer balance of credits. You are given a batch of commands that must be executed in order, and you must return the result of each one.
Input
commands: a list of command names.params: a list of parameter lists.params[i]holds the arguments forcommands[i]. The last element of every parameter list is the timestamp of that command. Timestamps never decrease from one command to the next.
The supported commands and their parameter lists are:
| Command | Parameters | Result |
|---|---|---|
"deposit" | [workspace_id, amount, timestamp] | bool |
"spend" | [workspace_id, amount, cashback_percent, delay, timestamp] | bool |
"transfer" | [from_id, to_id, amount, timestamp] | bool |
"merge" | [source_id, target_id, timestamp] | bool |
"get_balance" | [workspace_id, timestamp] | int |
"get_top_spenders" | [k, timestamp] | list[str] |
Output
Return a list with one result per command, in the same order.
Rules
Matured cashback. A cashback scheduled for time T becomes part of the balance as soon as the clock reaches T. Before executing any command with timestamp t, every pending cashback with maturity time <= t must already be credited. This includes commands that run at exactly the maturity time, so a spend or transfer at time t can use cashback maturing at t.
deposit. Adds amount to the workspace. If the ID does not exist yet, the workspace is created with that amount. If the ID is an alias left over from a merge, the credits go to the workspace it now resolves to, and the old ID is not recreated. Always returns True.
spend. Succeeds only if the workspace exists and its balance (including matured cashback) is at least amount. On success:
amountis subtracted from the balance and added to the workspace's cumulative spend.- A cashback of
amount * cashback_percent // 100(integer floor division) is scheduled to mature attimestamp + delay. - The command returns
True.
Otherwise nothing changes and it returns False. Spending the exact full balance is allowed.
transfer. Moves amount from from_id to to_id. It returns True only if both IDs exist, they resolve to different workspaces, and the source balance is at least amount. Otherwise nothing changes and it returns False. A transfer never creates a workspace, and it does not count as spending.
merge. Folds source_id into target_id.
- It returns
Falseif either ID does not exist, or if both IDs resolve to the same workspace. - Otherwise the source's current balance, its cumulative spend, and all of its still-pending cashbacks become the target's. From then on, every use of the source ID (or any ID that already pointed to it) refers to the target. The target's ID remains the canonical ID.
- It returns
True.
If a given ID was itself merged earlier, a merge involving it acts on the workspace it currently resolves to.
get_balance. Returns the workspace's balance at timestamp, including matured cashback, or -1 if the ID does not exist. Aliases resolve to their current workspace.
get_top_spenders. Returns up to k canonical workspace IDs, ordered by cumulative spend (all spends up to and including timestamp) from largest to smallest. Ties are broken by canonical ID in ascending lexicographic order. Only workspaces whose cumulative spend is greater than 0 are eligible, so the list may be shorter than k, or empty.
Constraints
- Up to
50,000commands. 1 <= timestamp <= 10^9, and timestamps are non-decreasing across the batch.1 <= amount <= 10^60 <= cashback_percent <= 1001 <= delay <= 10^61 <= k <= 100- Workspace IDs are alphanumeric strings of length 1 to 32 (hyphens may also appear in test data).
- Every command name is one of the six listed above.
Examples
Example 1
Input: run_credit_ledger(['deposit', 'spend', 'get_balance', 'get_balance', 'deposit', 'merge', 'get_balance', 'get_top_spenders'], [['team-a', 100, 1], ['team-a', 40, 10, 5, 2], ['team-a', 4], ['team-a', 7], ['team-b', 50, 8], ['team-a', 'team-b', 9], ['team-a', 10], [2, 10]])
Output: [True, True, 60, 64, True, True, 114, ['team-b']]
Hints
Hint 1
Handle merges with a union-find structure keyed by workspace ID. Always make the merge target the root, since its ID is the canonical one, and resolve every ID through find before using it.
Hint 2
Keep all scheduled cashbacks in a single min-heap ordered by maturity time. Before running each command, pop everything with maturity <= the command's timestamp and credit it.
Hint 3
Credit a matured cashback to the workspace its ID resolves to at maturity time, not at scheduling time. Then pending cashbacks follow merges automatically, with no extra work during the merge.
Hint 4
Store balance and cumulative spend only for root workspaces. On a merge, add the source's values into the target and delete the source's entries. For top spenders, filter spend > 0 and sort by (-spend, id).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Three concerns are independent, and each has a standard structure.
-
Identity and merges. Use a union-find (disjoint set) over workspace IDs. A merge makes the source's root point to the target's root. Every command first resolves its IDs with
find, so aliases of merged workspaces redirect automatically. The target must remain the root because its ID is the canonical one, so union-by-size is not used. Path compression alone is fast enough. -
Delayed cashback. Keep one global min-heap of
(maturity_time, sequence, workspace_id, amount). Timestamps never decrease, so before executing any command at timetwe pop and credit every entry with maturity<= t. The credit goes tofind(workspace_id)evaluated at maturity time. If the workspace was merged in the meantime, the cashback lands in the new owner, which implements "pending cashback moves with the merge" at no extra cost. -
Cumulative spend. Keep
spent[root]. A merge adds the source's total to the target and deletes the source's entry. For rankings, take the roots with spend > 0 and sort by(-spend, id), then slice the firstk.
Balances and spend totals are stored only for roots; a merge folds the source's values into the target.
Why it is correct
- Lazy equals eager. Because time never goes backwards, crediting matured cashbacks at the start of each command yields the same state as crediting each at its exact maturity moment. The inclusive
<=matches "on or before the timestamp", so spends and transfers at timetsee cashback maturing att. - Merges preserve everything. The balance and spend total are added to the target directly. Pending cashbacks follow through the
findcall at payout time. - Self-operations are caught after resolution.
transferandmergecompare roots rather than raw strings, so two IDs that were merged earlier are correctly rejected. - Failed operations change nothing. Every check happens before any state is modified.
- Ranking filter. Only workspaces with spend > 0 are listed, transfers never add to spend, and the IDs reported are roots, i.e. canonical IDs.
Complexity
Let n be the number of commands, W the number of workspaces and P the number of scheduled cashbacks (P <= n).
- Each cashback is pushed and popped once:
O(log P)each. findis amortized near-logarithmic thanks to path compression.get_top_spenderscostsO(W log W)per call with the full sort. This is acceptable for the stated limits, andheapq.nsmallest(k, ...)would reduce it toO(W log k).
Space is O(W + P).
Reference solution
import heapq
from typing import List
def run_credit_ledger(commands: List[str], params: List[List]) -> List:
parent = {}
balance = {}
spent = {}
pending = [] # (maturity_time, seq, workspace_id, amount)
seq = 0
out = []
def find(x):
if x not in parent:
return None
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
nxt = parent[x]
parent[x] = root
x = nxt
return root
def release(t):
while pending and pending[0][0] <= t:
_, _, wid, amt = heapq.heappop(pending)
r = find(wid)
if r is not None:
balance[r] += amt
for cmd, args in zip(commands, params):
t = args[-1]
release(t)
if cmd == "deposit":
wid, amount, _ = args
r = find(wid)
if r is None:
parent[wid] = wid
balance[wid] = amount
spent[wid] = 0
else:
balance[r] += amount
out.append(True)
elif cmd == "spend":
wid, amount, pct, delay, _ = args
r = find(wid)
if r is None or balance[r] < amount:
out.append(False)
else:
balance[r] -= amount
spent[r] += amount
reward = amount * pct // 100
heapq.heappush(pending, (t + delay, seq, r, reward))
seq += 1
out.append(True)
elif cmd == "transfer":
a, b, amount, _ = args
src = find(a)
dst = find(b)
if src is None or dst is None or src == dst or balance[src] < amount:
out.append(False)
else:
balance[src] -= amount
balance[dst] += amount
out.append(True)
elif cmd == "merge":
a, b, _ = args
src = find(a)
dst = find(b)
if src is None or dst is None or src == dst:
out.append(False)
else:
balance[dst] += balance.pop(src)
spent[dst] += spent.pop(src)
parent[src] = dst
out.append(True)
elif cmd == "get_balance":
wid, _ = args
r = find(wid)
out.append(-1 if r is None else balance[r])
elif cmd == "get_top_spenders":
k, _ = args
ranked = [(wid, s) for wid, s in spent.items() if s > 0]
ranked.sort(key=lambda item: (-item[1], item[0]))
out.append([wid for wid, _ in ranked[:k]])
else:
raise ValueError("Unknown command: " + cmd)
return out