Compute Credit Ledger with Expiration
Data Structure DesignAuto-graded · 18 test casesLast updated
Implement an in-memory ledger that manages time-limited credits with priority expiration and debt tracking.
You are building a ledger to manage time-limited compute credits. Users receive credit allocations that become invalid after a certain time, and when they use resources, the system must prioritize spending credits that will expire soonest to maximize value.
Your task is to implement a function that processes a sequence of ledger operations:
- grant: Add a credit allocation of a given amount, valid from a start time until an expiration time (exclusive).
- consume: Use credits at a given time, returning any outstanding debt after the operation.
- get_balance: Query the net balance (active credits minus any debt) at a given time.
Input
operations: A list of operation names, each one of"grant","consume", or"get_balance".arguments: A list of argument lists, one per operation:grant:[amount, timestamp, expiry]— addsamountcredits valid fromtimestampuntilexpiry(exclusive)consume:[amount, timestamp]— usesamountcredits attimestampget_balance:[timestamp]— queries the balance attimestamp
Output
Return a list of results, one per operation:
grant→Noneconsume→ integer representing outstanding debt after consumptionget_balance→ integer representing net balance (positive for surplus, negative for debt)
Behavior Rules
- Earliest-expiry consumption: When consuming, always use credits with the earliest expiration first.
- Expiration boundary: A credit batch with expiration time
ecannot be used at any timet >= e. - Debt accumulation: If a consume request exceeds available active credits, consume all active credits and record the shortfall as debt (negative balance).
- Debt settlement: When granting new credits while debt exists, the new credits immediately pay down the debt first. Only any surplus remains as active credits with the given expiration.
- Monotonic time: All timestamps are non-decreasing across operations.
- Expired grants: A grant that has already expired when issued (where
expiry <= timestamp) has no effect.
Constraints
1 <= len(operations) <= 2 * 10^50 <= amount <= 10^90 <= timestamp < expiry <= 10^9timestampis non-decreasing across all operations
Examples
Example 1
Input: compute_credit_ledger(['grant', 'grant', 'consume', 'get_balance', 'consume', 'get_balance', 'grant', 'get_balance'], [[100, 0, 10], [50, 2, 5], [70, 3], [4], [90, 8], [8], [30, 12, 20], [12]])
Output: [None, None, 0, 80, 10, -10, None, 20]
Example 2
Input: compute_credit_ledger(['grant', 'get_balance', 'consume', 'get_balance'], [[50, 0, 5], [5], [20, 6], [6]])
Output: [None, 0, 20, -20]
Hints
Hint 1
Use a min-heap keyed by expiration time to always access the soonest-expiring credits first.
Hint 2
Since time only moves forward, expired credits can be removed lazily at the start of each operation.
Hint 3
Track two values outside the heap: total active credits and accumulated debt. Either debt is zero or the heap is empty, never both.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge is to efficiently manage credits that expire at different times while always consuming the earliest-expiring ones first. The solution uses three components:
-
Min-heap ordered by expiration time: Each entry stores
(expiry, insertion_order, amount). The heap root is always the batch expiring soonest. The insertion order breaks ties deterministically. -
Active credit total: A running sum of all amounts currently in the heap, updated as batches are added or removed.
-
Outstanding debt: Tracks any consumption that exceeded available credits.
Algorithm
For each operation:
Expiration cleanup: Before processing any operation, pop all batches from the heap where expiry <= timestamp. Since timestamps never decrease, once a batch expires it stays expired.
grant: If the grant is still valid (expiry > timestamp) and positive:
- First apply it to pay down any outstanding debt
- Push any remaining amount to the heap with its expiration time
- If debt fully absorbs the grant, nothing is added to the heap
consume: Pop batches from the heap in expiry order, taking from each until the request is satisfied or the heap is empty. If a batch is only partially used, push the remainder back. Any unmet demand becomes additional debt. Return the total debt.
get_balance: Return active_sum - outstanding_debt. This is positive when credits exceed debt, negative when in debt.
Why It Works
- Priority rule: The min-heap ensures we always consume from the earliest-expiring batch.
- Expiration rule: Lazy expiration at each timestamp removes invalid batches before use.
- Debt rule: Debt only grows when all active credits are exhausted.
- Settlement rule: Grants offset debt immediately, preventing debt and active credits from coexisting incorrectly.
- Invariant: At any point, either debt is zero or the heap is empty (or both). This ensures the balance calculation is always correct.
Complexity
- Time: O(n log n) where n is the number of operations. Each credit batch is pushed once and popped at most once. Consume operations pop at most all n batches total across all calls.
- Space: O(n) for the heap storing up to n credit batches.
import heapq
from typing import List, Optional
def compute_credit_ledger(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
credit_heap = [] # min-heap: (expiry, insertion_order, amount)
active_sum = 0
outstanding_debt = 0
results = []
insertion_counter = 0
last_timestamp = None
def remove_expired(current_time):
nonlocal active_sum
while credit_heap and credit_heap[0][0] <= current_time:
_, _, amt = heapq.heappop(credit_heap)
active_sum -= amt
for op, args in zip(operations, arguments):
if op == "grant":
amt, ts, exp = args
else:
amt, ts = args if op == "consume" else (None, args[0])
if last_timestamp is not None and ts < last_timestamp:
raise ValueError("timestamps must be non-decreasing")
last_timestamp = ts
remove_expired(ts)
if op == "grant":
if exp > ts and amt > 0:
debt_paid = min(amt, outstanding_debt)
outstanding_debt -= debt_paid
amt -= debt_paid
if amt > 0:
heapq.heappush(credit_heap, (exp, insertion_counter, amt))
active_sum += amt
insertion_counter += 1
results.append(None)
elif op == "consume":
need = amt
while need > 0 and credit_heap:
exp_time, ins_order, available = heapq.heappop(credit_heap)
take = min(need, available)
need -= take
available -= take
active_sum -= take
if available > 0:
heapq.heappush(credit_heap, (exp_time, ins_order, available))
outstanding_debt += need
results.append(outstanding_debt)
elif op == "get_balance":
results.append(active_sum - outstanding_debt)
else:
raise ValueError("unknown operation")
return results