Expiring Compute Credits: Earliest-Expiry-First Ledger Simulation
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a credit ledger replaying a command list, spending the soonest-expiring grants first, with all-or-nothing spends and time-based expiry.
Expiring Credit Ledger
A compute platform hands out credits in separate grants. Each grant has a size and an expiry time. When a job runs, its cost is paid from whichever usable grants will expire soonest, so as little credit as possible goes to waste.
You are given a recorded sequence of ledger commands and must replay it, returning one result per command.
Commands
commands[i] is the name of the i-th command and params[i] is its list of arguments.
| Command | Arguments | Meaning | Result appended |
|---|---|---|---|
"add_grant" | [grant_id, amount, expire_at] | Register a grant of amount credits. | None |
"consume" | [timestamp, amount] | Try to spend amount credits at time timestamp. | True or False |
"get_balance" | [timestamp] | Report the total usable credits at time timestamp. | an integer |
Rules
- Validity. A grant is usable at time
tonly ift < expire_at. Att == expire_atit is already expired. - Clock. The ledger's "current time" starts at
0. Everyconsumeandget_balancecommand sets the current time to itstimestamp.add_granthas no timestamp and does not change the clock. - Late grants. If an
add_grantarrives withexpire_at <=the current time, the grant is already expired and has no effect. It still produces aNoneresult. Grants added withexpire_atgreater than the current time are valid from the moment they are added. - Spending order.
consumedraws from usable grants in increasingexpire_atorder. A grant is drained completely before the next one is touched. Grants with equalexpire_atexpire together, so the order among them cannot change any result. - All or nothing. If the total usable credit at
timestampis less thanamount, returnFalseand change nothing. Otherwise deduct exactlyamountand returnTrue. Spending exactly the full balance succeeds. - Balance.
get_balancereturns the sum of remaining credits over all grants usable attimestamp, or0if there are none. - Time order. Across all
consumeandget_balancecommands, timestamps never decrease.
Return the list of results, one per command and in the same order.
Constraints
1 <= len(commands) == len(params) <= 2 * 10^5commands[i]is one of"add_grant","consume","get_balance".1 <= amount <= 10^91 <= timestamp, expire_at <= 10^14grant_idis a unique, non-empty alphanumeric string. It does not affect any result.- Timestamps in
consumeandget_balancecommands are non-decreasing in command order.
Examples
Example 1
Input: process_ledger_ops(['add_grant', 'add_grant', 'consume', 'get_balance', 'consume', 'get_balance'], [['g1', 100, 50], ['g2', 50, 30], [10, 80], [20], [40, 70], [45]])
Output: [None, None, True, 70, True, 0]
Example 2
Input: process_ledger_ops(['add_grant', 'get_balance', 'consume'], [['g1', 50, 20], [20], [20, 10]])
Output: [None, 0, False]
Hints
Hint 1
Spending order and expiry order are the same order: always the smallest expire_at first. One min-heap keyed by expire_at can serve both purposes.
Hint 2
Because query times never go backward, a grant that has expired can never become usable again. Pop expired grants off the heap permanently before handling each consume or get_balance, and keep a running total of the credits still in the heap.
Hint 3
For consume, compare the running total with the amount before changing anything, so a failure leaves no trace. On success, repeatedly take from the heap top: pop it if fully used, otherwise reduce its remaining amount in place. Reducing it does not change its heap key.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two observations drive the design.
- Spending order equals expiry order. We always spend the grant that expires soonest, and expiry also removes grants soonest-first. A single min-heap keyed by
expire_at(ties broken by insertion order) covers both needs. - Time never moves backward. Once a grant has expired at some query time, it is expired for every later query. So expired grants can be deleted from the heap permanently. Before each
consumeorget_balance, pop while the heap top hasexpire_at <= timestamp.
We also keep active_total, the sum of remaining credits of all grants still in the heap. After pruning, it is exactly the usable balance.
get_balanceprunes and returnsactive_total.consumeprunes, then comparesactive_totalwith the requested amount. If the total is too small, it returnsFalsebefore touching any grant, which gives the all-or-nothing behavior. Otherwise it walks from the heap top: a grant with at most the needed amount left is popped entirely, and otherwise its remaining value is reduced in place. Only theremainingfield changes, not the heap key, so the heap stays valid. At most one grant is partially consumed.add_grantpushes onto the heap only ifexpire_atis greater than the current clock, because a grant that is already expired can never be used by any later query (times are non-decreasing).
Why it is correct
- After pruning, the heap contains exactly the grants with
expire_at > tand positive remaining credit, soactive_totalis the correct balance. - The heap top is always the usable grant with the smallest expiry, matching the required spending order.
- The sufficiency check happens before any mutation, so a failed consume changes nothing. If the check passes, the loop is guaranteed to finish before the heap empties.
- Grants with equal expiry expire at the same instant, so their relative order cannot change any balance or result.
Complexity
Each grant is pushed once and popped at most once, either by expiry or by being fully consumed. A consume does O(1) extra work for the single partially used grant.
- Time: O(Q log n) for Q commands and n grants.
- Space: O(n).
Reference solution
import heapq
from typing import List
def process_ledger_ops(commands: List[str], params: List[List]) -> List:
# Heap entries: [expire_at, insertion_order, remaining]
heap = []
active_total = 0
now = 0
order = 0
results = []
def drop_expired(t):
nonlocal active_total
while heap and heap[0][0] <= t:
entry = heapq.heappop(heap)
active_total -= entry[2]
for cmd, args in zip(commands, params):
if cmd == "add_grant":
_grant_id, amount, expire_at = args
if amount > 0 and expire_at > now:
heapq.heappush(heap, [expire_at, order, amount])
order += 1
active_total += amount
results.append(None)
elif cmd == "get_balance":
t = args[0]
now = t
drop_expired(t)
results.append(active_total)
elif cmd == "consume":
t, amount = args
now = t
drop_expired(t)
if active_total < amount:
results.append(False)
continue
need = amount
while need > 0:
top = heap[0]
if top[2] <= need:
need -= top[2]
active_total -= top[2]
heapq.heappop(heap)
else:
top[2] -= need
active_total -= need
need = 0
results.append(True)
else:
raise ValueError("unknown command: " + str(cmd))
return results