GPU Credits / GPU Credit 2
Medium · Coding · 75 min
Implement a GPU credit ledger GPUCredit. The platform grants GPU credits to users, where each grant has an activation timestamp and a validity duration; GPU usage deducts credits; and callers query the available balance at any timestamp. Across all 4 parts, the interface consists of the same three methods:
class GPUCredit:
def add_credit(self, credit_id: str, amount: int, timestamp: int, expiration: int) -> None: ...
def subtract(self, amount: int, timestamp: int) -> None: ...
def get_balance(self, timestamp: int) -> int | None: ...
All timestamps and amounts are integers.
Part 1: Credit Grants and Balance Queries
add_credit(credit_id, amount, timestamp, expiration): Grantsamountcredits valid on the closed interval[timestamp, timestamp + expiration](usable through the expiration timestamp itself, and expired starting at the next timestamp).credit_idmust be unique. A duplicatecredit_id,amount < 0, orexpiration < 0must raiseValueErrorwithout recording the failed call (so the same unused ID can still be granted later).get_balance(t): Returns the sum of remaining credits across all grants active at timestampt.- If no grant is active at timestamp
t, returnNone. If at least one grant is active attand the remaining balance is zero (e.g., anamount = 0grant), return0.
In Parts 1–3, all calls (including get_balance) arrive in non-decreasing timestamp order.
g = GPUCredit()
g.add_credit("a", 10, 0, 5) # active on [0, 5]
g.add_credit("b", 5, 3, 10) # active on [3, 13]
g.get_balance(5) # 15
g.get_balance(6) # 5, since "a" has expired
g.get_balance(14) # None
Part 2: Deductions — Earliest Expiration First
subtract(amount, timestamp): Deducts amount at timestamp (amount < 0 raises ValueError).
- Credits can only be deducted from grants active at
timestamp. - Consume from the active grant with the earliest expiration timestamp first; if it is insufficient, continue to the next earliest-expiring grant, spanning multiple grants as needed.
- Consumed credits are permanently spent: once an earlier-expiring grant later expires, credits deducted from it are never "refunded" back to other grants.
- If grants and deductions share the exact same
timestamp, process grants before deductions.
g = GPUCredit()
g.add_credit("a", 4, 1, 8) # active on [1, 9]
g.add_credit("b", 3, 2, 2) # active on [2, 4]
g.subtract(2, 3) # "b" expires earlier, so deduct 2 from "b"
g.get_balance(4) # 5 (a: 4 + b: 1)
g.get_balance(5) # 4 ("b" expired; its unused 1 is forfeited)
Part 3: Overdraft Debt and None Semantics
- If a deduction exceeds the total active balance at that timestamp, the uncovered remainder is recorded as debt.
- Every subsequent grant pays down existing debt first, and only the leftover amount enters available credit. If multiple grants share the same timestamp, earlier-expiring grants pay down debt first.
- Debt never expires with time; it can only be cleared by subsequent grants.
get_balance(t): ReturnsNoneif unpaid debt remains attor no grant is active att; otherwise returns the remaining active balance (0when active grants have been completely used up).
g = GPUCredit()
g.add_credit("a", 5, 0, 10)
g.subtract(8, 1) # leaves debt of 3
g.get_balance(2) # None
g.add_credit("b", 10, 3, 10) # repays 3 debt first, leaving 7 available
g.get_balance(3) # 7
Part 4: Out-of-Order Events (GPU Credit 2)
Drop the monotonic-arrival assumption from Parts 1–3: add_credit, subtract, and get_balance may now arrive in any order, and get_balance(t) is evaluated strictly by event timestamp:
- A query at timestamp
tdepends only on events with timestamp<= t; future events must never leak into earlier balances. - Late-arriving historical events take effect at their event timestamp and may retroactively change which grants absorbed later deductions.
- Regardless of arrival order, the same set of events must always produce identical query answers (which is why Part 3 defines deterministic tie-breaking at identical timestamps).
Self-test example: Grant 4 at t = 1 (valid through 9), grant 3 at t = 2 (valid through 4), and deduct 2 at t = 3. Even if subtract(2, 3) arrives first, querying t = 4 must return 5, t = 5 must return 4, and t = 2 must return 7.
g = GPUCredit()
g.subtract(2, 3) # arrives first
g.add_credit("a", 4, 1, 8)
g.add_credit("b", 3, 2, 2)
g.get_balance(4), g.get_balance(5) # (5, 4)
Clarifying Questions to Ask in an Interview
- Is the expiration boundary inclusive or exclusive? Is
expirationa duration or an absolute timestamp? - What happens when a deduction exceeds available balance: reject it, clamp at
0, or track overdraft debt? Do future grants pay off past overdrafts? - Should zero remaining balance be distinguished from having no active grants (
0vsNone)? - At the same timestamp, are grants processed before deductions? Among simultaneous grants, which one repays debt first?
- Do events arrive in chronological order, and can queries ask about past timestamps?
- What is the scale of events vs. queries — do we need something faster than replaying all events per query?
Step-by-step walkthrough
Part 1 · Core idea: log raw events and replay on query
A user's GPU balance at timestamp
tdepends on the entire history of grants and debits up tot: which grants were active when each debit happened, which ones expired unused, and whether any debt is still owed. The cleanest and least error-prone architecture is event replay:add_creditandsubtractonly validate inputs and append the raw event to a list.get_balance(t)collects all events withevent_time <= t, sorts them into chronological order, and simulates them from start to finish.
Recorded events: t=1 grant a(4, ends 9) t=2 grant b(3, ends 4) t=3 debit 2 get_balance(4): replay t=1, 2, 3 -> debit spends 2 from earlier-expiring b at t=4: a has 4, b has 1 (still valid since 4 <= 4) --> returns 5 get_balance(5): replay t=1, 2, 3 -> at t=5, b has expired (4 < 5) only a remains with 4 --> returns 4Replaying from scratch on every query keeps the code short and transparent, and as a bonus it will handle Part 4's out-of-order arrivals automatically because replay sorts by event time, not arrival order.
Part 1 · Validate and record credit grants
Each
credit_idmust be unique, and negativeamountorexpirationmust raiseValueErrorwithout registering the ID. That means we must run every validation check before callingself.used_ids.add(credit_id), so a rejected call never blocks a future valid call with the samecredit_id.Since a grant is valid on the closed interval
[timestamp, timestamp + expiration], we store(start_time, end_time, amount)directly.class GPUCredit: def __init__(self): # grants: list of (start_time, end_time, amount) tuples; valid on [start_time, end_time] self.grants = [] # debits: list of (debit_time, amount) tuples self.debits = [] # used_ids: set of credit_id strings that passed validation self.used_ids = set() def add_credit( self, credit_id: str, amount: int, timestamp: int, expiration: int ) -> None: if credit_id in self.used_ids: raise ValueError(f"duplicate credit id: {credit_id}") if amount < 0 or expiration < 0: raise ValueError("amount and expiration must be >= 0") self.used_ids.add(credit_id) end_time = timestamp + expiration self.grants.append((timestamp, end_time, amount))Part 1 · Sum valid grants and distinguish `0` from `None`
In Part 1 there are no debits yet, so the balance at
timestampis simply the sum of all grants whose[start_time, end_time]interval containstimestamp.Pay careful attention to
Noneversus0: - If no grant coverstimestamp, returnNone. - If at least one grant coverstimestamp— even a grant withamount == 0— return0(or the positive sum).We write
has_valid_grant(timestamp)as its own helper because Parts 2–4 will reuse the exact same check.def has_valid_grant(self, timestamp: int) -> bool: """Return True if at least one grant's [start_time, end_time] covers `timestamp`.""" for start_time, end_time, _ in self.grants: if start_time <= timestamp <= end_time: return True return False def get_balance(self, timestamp: int) -> int | None: if not self.has_valid_grant(timestamp): return None total_balance = 0 for start_time, end_time, amount in self.grants: if start_time <= timestamp <= end_time: total_balance += amount return total_balance✅ Submit now — Part 1 tests should pass.
Part 2 · Record debits and sort events into deterministic replay order
subtractsimply checksamount >= 0and logs(timestamp, amount). To replay grants and debits together, we pack every event with time<= timestampinto a 4-tuple(event_time, event_kind, end_time, amount)and call Python's built-in.sort():Tuple layout: (event_time, event_kind, end_time, amount) | | | | | +-- 3rd: earlier-expiring grants first (for Part 3 debt) | +------------- 2nd: GRANT (0) before DEBIT (1) at same timestamp +-------------------------- 1st: chronological orderFiltering to
<= timestampguarantees future events never leak into historical balance queries.GRANT = 0 DEBIT = 1 class GPUCredit: # ... __init__, add_credit, has_valid_grant ... def subtract(self, amount: int, timestamp: int) -> None: if amount < 0: raise ValueError("amount must be >= 0") self.debits.append((timestamp, amount)) def collect_sorted_events( self, timestamp: int ) -> list[tuple[int, int, int, int]]: events = [] for start_time, end_time, amount in self.grants: if start_time <= timestamp: events.append((start_time, GRANT, end_time, amount)) for debit_time, amount in self.debits: if debit_time <= timestamp: events.append((debit_time, DEBIT, 0, amount)) events.sort() return eventsPart 2 · Replay grants and earliest-expiry-first debits
During replay, we keep a list
active_grantswhere each entry is a two-element list[end_time, remaining_amount]. At every event with timestampevent_time:- Prune expired grants first: keep only entries with
end_time >= event_time. Why prune before every event instead of only at the end ofget_balance? Because if grantaexpired att = 2, a debit att = 4must skipaand deduct frombinstead! - If
GRANT: append[end_time, amount]toactive_grants. - If
DEBIT: sortactive_grantsso the smallestend_timecomes first, and walk through the list deductingmin(grant[1], remaining_to_spend)until the debit is satisfied.
After the loop finishes, prune once more at the query
timestampand sum what remains.def prune_expired( active_grants: list[list[int]], current_time: int ) -> list[list[int]]: """Keep only grants whose inclusive end_time is still >= current_time.""" still_valid = [] for grant in active_grants: end_time = grant[0] if end_time >= current_time: still_valid.append(grant) return still_validdef get_balance(self, timestamp: int) -> int | None: active_grants = [] for event_time, event_kind, end_time, amount in self.collect_sorted_events(timestamp): active_grants = prune_expired(active_grants, event_time) if event_kind == GRANT: active_grants.append([end_time, amount]) else: active_grants.sort() remaining_to_spend = amount for grant in active_grants: if remaining_to_spend == 0: break used = min(grant[1], remaining_to_spend) grant[1] -= used remaining_to_spend -= used active_grants = prune_expired(active_grants, timestamp) if not self.has_valid_grant(timestamp): return None total_balance = 0 for end_time, remaining in active_grants: total_balance += remaining return total_balanceNotice we leave
[end_time, 0]entries insideactive_grantswhen a grant is fully spent — adding0at the end does not changetotal_balance, andhas_valid_grant(timestamp)still correctly returns0(notNone) while that grant's time window is active.✅ Submit now — Part 2 tests should pass.
- Prune expired grants first: keep only entries with
Part 3 · Track overdraft debt and repay it with new grants
Part 3 requires only three small additions inside
get_balance:- Create debt: After scanning all
active_grantsfor a debit, any leftoverremaining_to_spendis added todebt. - Repay debt: When a
GRANTarrives,repaid = min(debt, amount)pays downdebtfirst, and onlyamount - repaidentersactive_grants. Becausecollect_sorted_eventsalready sorted simultaneous grants byend_time, earlier-expiring grants automatically repay debt first! - Return
Nonewhile in debt: At the end,if debt > 0 or not self.has_valid_grant(timestamp): return None.
Overdraft trace: t=0: grant a(5, ends 10) -> debt=0, active=[[10, 5]] t=1: debit 8 -> uses 5 from a, 3 uncovered -> debt=3, active=[[10, 0]] get_balance(2) -> debt=3 > 0 -> None t=3: grant b(10, ends 13) -> repaid=min(3,10)=3 -> debt=0, active=[[10, 0], [13, 7]] get_balance(3) -> debt=0 and valid grant exists -> 7def get_balance(self, timestamp: int) -> int | None: active_grants = [] debt = 0 for event_time, event_kind, end_time, amount in self.collect_sorted_events(timestamp): # Step 1: Drop grants that expired before this event occurred. active_grants = prune_expired(active_grants, event_time) if event_kind == GRANT: # Step 2 (Grant): Repay any existing overdraft debt first; keep the remainder. repaid = min(debt, amount) debt -= repaid remaining = amount - repaid active_grants.append([end_time, remaining]) else: # Step 3 (Debit): Spend from earliest-expiring valid grants first. active_grants.sort() remaining_to_spend = amount for grant in active_grants: if remaining_to_spend == 0: break used = min(grant[1], remaining_to_spend) grant[1] -= used remaining_to_spend -= used debt += remaining_to_spend # Step 4: Drop grants expired before `timestamp`, then check debt and validity. active_grants = prune_expired(active_grants, timestamp) if debt > 0 or not self.has_valid_grant(timestamp): return None total_balance = 0 for end_time, remaining in active_grants: total_balance += remaining return total_balance✅ Submit now — Part 3 tests should pass.
- Create debt: After scanning all
Part 4 · Verify why out-of-order events already work
In Part 4,
add_credit,subtract, andget_balancecan arrive in any order. Let's verify every guarantee in our design:- Arrival order is ignored:
add_creditandsubtractonly append tuples; neither touches any running balance. - Deterministic tie-breaking:
collect_sorted_eventssorts by(event_time, event_kind, end_time, amount). Even if two grants arrive at the sameevent_timein reverse order, the earlier-expiring one always repays debt first; if two grants also share the exact sameend_time, every remaining credit unit expires at the same moment anyway. - No future leakage:
start_time <= timestampanddebit_time <= timestampfilter out everything aftertimestamp.
Arrival order: 1st subtract(2, t=3) 2nd add("a", 4, t=1..9) 3rd add("b", 3, t=2..4) Replay for get_balance(2): events <= 2 are [t=1 a(4), t=2 b(3)] (t=3 debit excluded!) -> 7 Replay for get_balance(4): events <= 4 are [t=1 a(4), t=2 b(3), t=3 debit(2)] -> 5 Replay for get_balance(5): same replay, then prune at t=5 drops b (end 4 < 5) -> 4Zero lines of code need to change for Part 4.
✅ Submit now — all tests should pass.
- Arrival order is ignored:
Intuition & how it works
Think of GPU credits like a stack of store gift cards with different expiration dates: whenever you buy something, a smart cashier spends from the gift card that expires soonest so your longer-lasting cards stay intact. If your mail arrives out of order — say a restaurant receipt from Wednesday shows up before the gift card you actually received on Tuesday — you cannot just maintain one live wallet total; instead, you lay every card and receipt on a table sorted by date and replay them from Monday forward. That pattern is called event replay (or event sourcing, meaning we store an append-only log of raw events and compute the state at any timestamp t by re-running events in chronological order).
Why do simpler formulas fall apart? You cannot compute the balance as total_valid_grants - total_debits because which grant absorbed an earlier debit changes what expires later: if a short-lived grant paid for yesterday's job and then expired today, your long-lived grant is still completely untouched! Similarly, maintaining only a single running state works when timestamps strictly increase (Parts 1–3), but breaks immediately in Part 4 when a backdated grant arrives late and retroactively absorbs a past debit that had previously eaten into a long-lived grant or created debt.
Let's walk through the out-of-order example where subtract(2, t=3) arrives first, followed by a (4 credits on the closed interval [1, 9], meaning both endpoints t=1 and t=9 are included) and b (3 credits on [2, 4]):
Sorted events <= 5:
1. (t=1, GRANT, end=9, amt=4) -> debt=0; active_grants = [[9, 4]]
2. (t=2, GRANT, end=4, amt=3) -> debt=0; active_grants = [[9, 4], [4, 3]]
3. (t=3, DEBIT, end=0, amt=2) -> sort active_grants -> [[4, 3], [9, 4]]
deduct 2 from b (end=4) -> [[4, 1], [9, 4]]
At query t=4: prune keeps end >= 4 -> [[4, 1], [9, 4]] -> balance = 1 + 4 = 5
At query t=5: prune keeps end >= 5 -> [[9, 4]] (b's leftover 1 expired!) -> balance = 4
Complexity
Let E be the total number of recorded events (grants + debits), and let A (A <= E) be the maximum number of simultaneously active grants during a replay.
add_creditandsubtract:- Time:
O(1)average. Checkingcredit_id in self.used_idsand inserting into a hash set takeO(1)average time, and appending a tuple toself.grantsorself.debitstakesO(1)amortized time. - Space:
O(E)total across all calls, since we store one small tuple per valid grant or debit plus one ID string per grant inself.used_ids.
- Time:
get_balance(timestamp):- Time:
O(E log E + E * A log A). Filtering allEevents takesO(E), sorting up toEevent tuples takesO(E log E), and during replay each event prunesactive_grantsinO(A)while debit events also sortactive_grantsinO(A log A). Finally,has_valid_grantscans the grant list once inO(E). - Space:
O(E). The filteredeventslist andactive_grantslist each hold at mostEitems during the query.
- Time:
Edge cases
- Query earlier than every grant (
t = 0when earliest grant starts att = 1):has_valid_grant(0)isFalse, soget_balance(0)returnsNone. - Query on the exact expiration timestamp (
t == start + expiration): Because validity is a closed interval[start, end],end_time >= current_timekeeps the grant active; att + 1it expires. - Zero-duration grant (
expiration == 0): Valid at the single instant[timestamp, timestamp]and expired attimestamp + 1. - Zero-amount grant (
amount == 0) or completely spent grant: As long asdebt == 0and at least one grant's[start, end]coverstimestamp,get_balance(timestamp)returns0, notNone. - Rejected
add_creditcall: Validation runs beforeself.used_ids.add(credit_id), so a call withamount < 0orexpiration < 0raisesValueErrorwithout reservingcredit_id. - Debt outliving expired grants: Debt never expires on its own; even long after all grants expire,
debt > 0forcesget_balanceto returnNoneuntil future grants repay every unit of debt.
Common mistakes
- Using
<instead of<=on expiration (end_time > current_time): That treats[start, end]as half-open and prematurely drops credits on their final valid timestamp. Keep grants wheneverend_time >= current_time. - Pruning expired grants only at the end of
get_balance: If you forget to prune right before each debit atevent_time, a debit att = 4will illegally spend credits from a grant that already expired att = 2. - Returning
Nonewhenevertotal_balance == 0:0means "a valid grant covers this timestamp, and zero credits remain";Nonemeans either "unpaid debt exists" or "no grant covers this timestamp at all." Be especially careful if you later optimizeactive_grantsinto a heap that pops depleted grants — an empty heap can still have0balance if a depleted grant's[start, end]window hasn't expired yet! - Breaking same-timestamp grant ties by arrival order: Suppose
debt = 3and two grants arrive att = 5:g1(3credits expiring at6) andg2(3credits expiring at100). Usingg1to repay debt leaves3credits untilt = 100, whereas usingg2leaves0aftert = 6. Includingend_timein the event sort tuple ensuresg1always pays debt first regardless of arrival order.
Follow-up questions
- How do we speed up replay from
O(E * A log A)toO(E log E)? Replace theactive_grantslist with a min-heap (heapq— a binary tree stored in an array that pops the smallest[end_time, remaining]inO(log A)time) and use lazy deletion (whenever we process an event atevent_time, repeatedly pop the heap top whileheap[0][0] < event_time). Each grant is pushed and popped at most once across the entire replay, so all heap operations sum toO(E log A). - What if events are guaranteed in chronological order (Parts 1–3 only)? Then we don't need to replay from scratch on each query! We can maintain one persistent min-heap of active grants, one
debtinteger, and trackmax_end_time_seen(since timestamps never decrease,max_end_time_seen >= timestamptells us inO(1)whether any grant coverstimestamp), making every operationO(log A)amortized. - What if queries are frequent (
Qis huge) AND events can still arrive out of order? Keep events in a sorted list (bisect.insort) and save periodic snapshots / checkpoints (deep copies of(debt, heap)everyK = sqrt(E)events). A query attimestampjumps to the latest checkpoint<= timestampand replays at mostKevents; an out-of-order historical insert only invalidates checkpoints after its timestamp. - How would this look in a production billing service? Store an immutable per-account event log partitioned by
account_id, attach an idempotency key (a unique client-generated request ID so network retries never double-chargesubtract), and represent currency/GPU-seconds as integer micro-units rather than floating-point numbers to avoid rounding drift.
More OpenAI problems
- Infection Spread / Cellular Automata
- Social Network / Follow Graph
- Poker Simulation
- Classifier with Noisy Annotators
- Durable Key-Value Store Serialization
- NumPy Puzzle: 1-NN Vectorization → Wx+b Network
- Memory Allocator
- Transformer Bug Hunt
- Distributed Machine Cluster Count and Topology
- Autograd / Manual Backprop + Hillis-Steele Scan