Prepaid Compute Credit Tracker with Replay-Safe Events
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a per-tenant credit ledger driven by a command list, rejecting overdrafts and repeated event ids while tracking balances in a hash map and a set.
Prepaid Compute Credit Tracker
A shared compute cluster hands out prepaid credits to tenants. Each tenant has an integer balance that changes through events. You must simulate a small ledger that is driven by a list of commands.
Event format
An event is a dictionary with these keys:
tenantId(string): the tenant whose balance changes.delta(integer): a signed amount. Positive adds credit, negative removes credit.id(string, optional): a unique identifier for the event. If the key is absent, the event has no identifier.
Ledger rules
- Every tenant starts at balance
0. A tenant never seen before has balance0. - An event is accepted only if both conditions hold:
- Its
idis absent, or itsidhas not already been used by a previously accepted event. - The tenant's balance after adding
deltawould be>= 0.
- Its
- An accepted event adds
deltato the tenant's balance and, if it has anid, records that id as used. - A rejected event changes nothing. In particular, the id of a rejected event is not recorded, so that id may still be used by a later event.
- Events without an
idare never treated as duplicates. - A
deltaof0is a valid event and is accepted if its id is unused. - A deduction that brings the balance exactly to
0is allowed. - Ids are tracked globally across all tenants, not per tenant.
Commands
You receive two parallel lists, operations and arguments. The i-th command is operations[i] with argument list arguments[i]. Process the commands in order.
| Operation | Arguments | Behavior | Output entry |
|---|---|---|---|
"init" | [events] where events is a list of events | Discard all balances and all recorded ids, then apply each event in the given order using the rules above. Events that are rejected are silently skipped. | None |
"getBalance" | [tenantId] | Look up the current balance. | the integer balance (0 for an unknown tenant) |
"applyEvent" | [event] | Process a single event using the rules above. | True if accepted, False if rejected |
If no init command has been issued yet, the ledger behaves as if it were empty. Another init later in the list resets everything again.
Task
Return a list with one output entry per command, in the same order as the commands.
Constraints
len(operations) == len(arguments)- Operation names are exactly
"init","getBalance", or"applyEvent". deltais an integer; balances fit comfortably in Python integers.tenantIdvalues are non-empty strings;idvalues, when present, are strings.- Each command must run in O(1) average time, except
init, which is linear in the number of events it contains.
Examples
Example 1
Input: run_credit_ledger(['init', 'getBalance', 'applyEvent', 'getBalance', 'applyEvent', 'getBalance', 'applyEvent', 'getBalance'], [[[{'tenantId': 'gpu-a', 'delta': 10, 'id': 'e1'}, {'tenantId': 'gpu-b', 'delta': 4, 'id': 'e2'}]], ['gpu-a'], [{'tenantId': 'gpu-a', 'delta': -3, 'id': 'e3'}], ['gpu-a'], [{'tenantId': 'gpu-a', 'delta': 5, 'id': 'e3'}], ['gpu-a'], [{'tenantId': 'gpu-a', 'delta': -8, 'id': 'e4'}], ['gpu-a']])
Output: [None, 10, True, 7, False, 7, False, 7]
Hints
Hint 1
Two hash-based structures are enough: a dictionary from tenant to balance and a set of ids that have been used by accepted events.
Hint 2
Write one helper that decides whether an event is accepted and applies it. Use it for both `init` and `applyEvent` so the rules cannot drift apart.
Hint 3
Only record an event's id after you know it was accepted, and make sure `init` replaces both the dictionary and the set with fresh empty ones.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two hash-based structures:
balances: maps a tenant to its current balance. Missing tenants count as0.used_ids: a set containing the ids of all accepted events.
A single helper, apply(event), implements the acceptance rule:
- If the event has an id that is already in
used_ids, reject it. - Compute
balances.get(tenant, 0) + delta. If it is negative, reject it. - Otherwise store the new balance, add the id (if any) to
used_ids, and accept.
The main loop walks through the commands:
initreplaces both structures with empty ones, then callsapplyfor each event and ignores the results. It outputsNone.getBalanceoutputsbalances.get(tenant, 0).applyEventoutputs the boolean returned byapply.
Why it is correct
Each balance always equals the sum of the deltas of accepted events for that tenant, because the only place a balance is modified is the accepting branch of apply, and rejected events return before any mutation. Ids are added only on acceptance, so a rejected id stays reusable, as the rules require. Because init and applyEvent share the same helper, they obey identical rules. Resetting both structures in init guarantees no state leaks from earlier commands. Balances never go negative, since an event that would cause it is rejected before being applied.
Complexity
applyEvent,getBalance: O(1) average time.initwithnevents: O(n) time.- Space: O(T + K), where T is the number of distinct tenants and K the number of accepted ids.
Reference solution
from typing import List
def run_credit_ledger(operations: List[str], arguments: List[List]) -> List[object]:
balances = {}
used_ids = set()
results = []
def apply(event):
tenant = event["tenantId"]
delta = event["delta"]
event_id = event.get("id")
if event_id is not None and event_id in used_ids:
return False
new_balance = balances.get(tenant, 0) + delta
if new_balance < 0:
return False
balances[tenant] = new_balance
if event_id is not None:
used_ids.add(event_id)
return True
for operation, args in zip(operations, arguments):
if operation == "init":
balances = {}
used_ids = set()
for event in args[0]:
apply(event)
results.append(None)
elif operation == "getBalance":
results.append(balances.get(args[0], 0))
elif operation == "applyEvent":
results.append(apply(args[0]))
else:
raise ValueError("Unknown operation")
return results