Expiring Compute Credits: Offline Ledger Replay
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Replay a shuffled log of credit grants, spends and balance queries in time order, spending the soonest-expiring credits first, using a heap and sorting.
You are given the complete log of operations performed on a compute-credit ledger. The log is not in chronological order, but each operation carries its own timestamp. Compute the answer to every operation as if all operations had been applied in timestamp order.
Operations
Each operation is a list in one of these forms:
["add_credit", id, amount, timestamp, expiration]grantsamountcredits that can be used during the half-open interval[timestamp, timestamp + expiration). The credits are usable attimestampitself but no longer usable attimestamp + expiration. Theidis only a label, and two grants with the sameidare independent.["charge", amount, timestamp]tries to spendamountcredits attimestamp.["get_balance", timestamp]asks for the total number of usable (granted, started, not yet expired, not yet spent) credits attimestamp.
Rules
- Chronological replay. Operations take effect in increasing order of
timestamp, regardless of their position in the input list. - Ties at the same timestamp. All
add_creditoperations happen first, then allchargeoperations, then allget_balanceoperations. Within the same kind, operations are handled in input order. - Usable credits. A charge at time
tcan only use grants withtimestamp <= t < timestamp + expirationthat still have credits left. A grant withamount <= 0orexpiration <= 0is ignored entirely. - Partial charges. A charge spends
min(amount, current balance)credits. It never fails. It takes as much as is available, up to the requested amount. - Spending order. A charge takes credits from the grant that expires soonest first, then the next soonest, and so on. If two grants expire at the same moment, which one is drained first does not affect any output.
Output
Return a list with one entry per input operation, in the original input order:
Noneforadd_credit- the number of credits actually spent for
charge - the balance for
get_balance
Constraints
1 <= len(operations) <= 10^5- Timestamps and expirations are integers; timestamps may be repeated and may appear in any order.
- Charge amounts are positive integers. Grant amounts are integers (non-positive ones are ignored).
- The expected running time is
O(n log n).
Examples
Example 1
Input: replay_credit_ledger([['add_credit', 'gpu-a', 10, 10, 10], ['add_credit', 'gpu-b', 5, 0, 100], ['charge', 8, 12], ['get_balance', 12], ['get_balance', 20]])
Output: [None, None, 8, 7, 5]
Example 2
Input: replay_credit_ledger([['add_credit', 'x', 7, 5, 5], ['get_balance', 5], ['charge', 10, 7], ['get_balance', 7], ['get_balance', 10]])
Output: [None, 7, 7, 0, 0]
Hints
Hint 1
Because the whole log is known in advance, you do not need an online structure. Sort all operations by (timestamp, kind, input index), with kind order add < charge < query, and sweep once.
Hint 2
Keep a min-heap of grants keyed by expiry time. Before handling each event at time t, pop every grant whose expiry is <= t and subtract its remaining amount from a running balance.
Hint 3
A charge spends min(amount, balance). To spend it, repeatedly take the heap top (soonest expiry), use as much as needed, and push it back with the leftover if any. Store the answer at the operation's original index.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The entire log is available up front, so there is no need for a clever online structure. Reorder the operations chronologically and simulate them once.
- Convert each operation into an event
(timestamp, kind, input_index, amount, expiration), where kind is 0 foradd_credit, 1 forchargeand 2 forget_balance. Sorting these tuples gives exactly the required order: by time, then adds, charges and queries, then input order. - Sweep through the sorted events while maintaining:
- a min-heap of live grants ordered by expiry time, each with its remaining amount, and
- a running
balance, the sum of remaining amounts in the heap.
- Before each event at time
t, pop every grant on top of the heap withexpiry <= tand subtract its leftover frombalance. Since the heap is ordered by expiry, the expired grants are always at the top. - Handle the event:
- add_credit: if the amount and expiration are positive, push the grant and increase
balance. - charge: spend
min(amount, balance). Repeatedly pop the soonest-expiring grant, take what is needed, and push it back with any leftover. Record the spent amount. - get_balance: record
balance.
- add_credit: if the amount and expiration are positive, push the grant and increase
- Write each result into the slot of the original input index.
Why it is correct
- Sorting by
(timestamp, kind, index)reproduces the required order, including the tie rules at equal timestamps. - Expiring before every event means the heap only holds grants with
expiry > t. Grants that have not started yet are never in the heap, because their add event has not been processed. So the heap contains exactly the usable grants. balancealways equals the sum of remaining amounts in the heap, somin(amount, balance)is exactly what can be spent.- Taking from the heap top always uses the soonest-expiring grant, which is the required spending order.
- The half-open window is respected: a grant with
expiry == tis removed before the event attruns.
Complexity
- Sorting:
O(n log n). - Each grant is pushed once and popped for expiry at most once. Each charge step either exhausts a grant (a pop paid for by its push) or ends the charge, so at most one extra push-back per charge. The total heap work is
O(n log n). - Space:
O(n).
Reference solution
import heapq
from typing import List, Optional
def replay_credit_ledger(operations: List[List]) -> List[Optional[int]]:
ADD, CHARGE, QUERY = 0, 1, 2
events = []
for idx, op in enumerate(operations):
name = op[0]
if name == "add_credit":
_, _label, amount, ts, ttl = op
events.append((ts, ADD, idx, amount, ttl))
elif name == "charge":
_, amount, ts = op
events.append((ts, CHARGE, idx, amount, 0))
elif name == "get_balance":
_, ts = op
events.append((ts, QUERY, idx, 0, 0))
else:
raise ValueError("unknown operation")
events.sort()
answers: List[Optional[int]] = [None] * len(operations)
heap = [] # (expiry, tie, remaining)
balance = 0
tie = 0
for ts, kind, idx, amount, ttl in events:
# Drop grants that have expired by now.
while heap and heap[0][0] <= ts:
_, _, left = heapq.heappop(heap)
balance -= left
if kind == ADD:
expiry = ts + ttl
if amount > 0 and expiry > ts:
heapq.heappush(heap, (expiry, tie, amount))
tie += 1
balance += amount
elif kind == CHARGE:
spent = min(amount, balance)
answers[idx] = spent
need = spent
while need > 0:
expiry, t, left = heapq.heappop(heap)
use = min(left, need)
left -= use
need -= use
if left > 0:
heapq.heappush(heap, (expiry, t, left))
balance -= spent
else:
answers[idx] = balance
return answers