A GPU credit ledger with expiring credits
OpenAI candidates report this question from phone screens and onsites, more often than any other OpenAI coding question but one (7 reports). It starts with a statement like this one, and only its first level:
Build a ledger for GPU credits. Timestamps and amounts are integers. Calls can arrive in any timestamp order: a grant or a spend recorded now can land before a balance you already read, and the balance must reflect it.
grant(credit_id, amount, start)addsamountcredits that count from timestarton.spend(amount, timestamp)uses credits attimestamp.balance(timestamp)returns what's left at that time: every grant withstart <= timestamp, minus every spend at or beforetimestamp.A repeated
credit_id, or an amount that isn't positive, raisesValueErrorand changes nothing.
Call Returns grant("A", 10, 0)grant("B", 5, 3)spend(4, 2)balance(2)6balance(3)11spend(3, 1)balance(2)3grant("A", 7, 5)raises ValueError
spend(3, 1) comes in after the balances were read, and it still happened at time 1. So the balance at 2 drops from 6 to 3.
Level 1 is a sum. Level 2 makes credits expire: a credit can pay while start <= t < expires, and each spend draws from the usable credit that expires soonest. Level 3 adds overdraft: once a spend needs more than there is, every balance from then on is None, and a grant recorded later can clear it.
You don't write it yet. First you build a heap, the structure that always knows which credit expires soonest, and learn to replay calls in time order. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.
A heap is a cheaper cousin of sorting: it keeps only the smallest item in its place, which costs far less than sorting everything again after each change. Heaps come back all through the coding builds, where small systems grow in levels: the cache's expiry sweep, the billboard rotation and the work queue's leases each keep a heap of deadlines.