What they’re really asking
If you only remember one thing, say this in the first minute: “I’ll write my assumptions at the top, then build the simplest correct ledger with a few tests: one heap of grants per user, soonest expiry first, and a spend that checks the total before it touches anything. Every method takes the time as an argument, so tests are exact. When events can arrive late, I’ll switch to storing the events in time order and replaying them, because a late grant changes which credits an earlier spend used. Each rule lives in one function, so each new requirement is a small change.”
The rest of this page explains each part of that answer.
The interviewer wants to know whether you can produce a lot of correct, tested code in one session, and keep it easy to change when the rules move.
This is not a normal algorithm question. A LeetCode problem has one fixed statement and one trick. Here the ledger itself is simple: add credits, take credits away, report what is left. The round is decided by the second and third requirement: events that arrive late, a new spending order, a report nobody mentioned at the start. Your first version either absorbs those changes in a few lines or forces a rewrite you don’t have time for.
Hello Interview relays an OpenAI Staff candidate on this kind of round: “The coding problem question was rather long, use the interviewer to focus on important parts” (Hello Interview).
Clarify first
Each of these answers changes the code. Ask them in the first few minutes:
- Expiry boundary: is a credit usable at the exact instant it expires? Assume no. A credit is usable only
strictly before
expires_at; this is called a half-open (or exclusive) boundary. - Spending order: soonest expiry first? Assume yes, because it wastes the least, and expect it to change.
- Overdraft: if a spend is bigger than the balance, reject the whole spend and change nothing? Assume yes.
- Time order: do events arrive sorted by time? Assume yes for now, and say you expect this to change.
- Ties: a grant and a spend at the same timestamp: the grant applies first.
- Units: integer credits and integer timestamps. Floats in a ledger invite rounding bugs.
Write these as a comment block at the top of the file so the interviewer can correct them in one glance. Say it like this: “These are my assumptions. Stop me if any is wrong, because each one changes a line of code.”
Answer
Words you need first
- A grant gives a user some credits that expire at a set time.
- A spend uses credits at a given time. If there aren’t enough, it is an overdraft.
- The balance at time t is the total of credits that are unspent and unexpired at t.
- An event is one grant or one spend with its timestamp. Replay means rebuilding the state by applying the events again in time order, the way a database rebuilds itself from its write-ahead log.
One user, four stages
Follow one user, Ana, through the whole round. Each row is a new event or a new rule. (The balances were checked by running the family walkthrough’s stage-4 code on 2026-10-12.)
| Stage | Event or new rule | What the ledger says | What to say in the interview |
|---|---|---|---|
| 1 | Grant 100 at t=0, expiring at t=50 (G1); spend 60 at t=10 | balance at t=10 is 40 | ”Check the total first, then take credits. A rejected spend changes nothing.” |
| 2 | A grant of 100 arrives late: it happened at t=5 and expires at t=20 (G2) | the t=10 spend now draws on G2; balance at t=10 is 140, at t=25 is 100 | ”A late event changes which credits an earlier spend used. I’ll store events and replay them.” |
| 3 | Promo credits go first. Grant 20 promo at t=30, expiring at t=60 (G3); spend 50 at t=35 | 20 from G3, then 30 from G1; balance at t=35 is 70 | ”Only the ordering function changes.” |
| 4 | Report credits that expired unused in [0, 61) | 40 from G2 + 70 from G1 + 0 from G3 = 110 | ”Four lines, because replay already knows what each grant held when it expired.” |
Stage 1: a heap per user
A min-heap always hands you its smallest item cheaply (O(log n)). Keep one per user, ordered by expiry, and its
top is the next credit to spend. A spend first checks that the unexpired credit covers it, then takes credits from
the top of the heap until it is paid. Expired grants are not searched for; they are dropped the next time they
reach the top. This is called lazy expiry, the same trick a cache with a time-to-live uses. Every method takes
at; nothing reads the clock.
def spend(self, user, amount, at):
live = self._live(user, at) # pops grants with expires_at <= at
if sum(g.remaining for _, _, g in live) < amount:
raise InsufficientCredits(user) # checked before any mutation
while amount:
_, _, g = live[0] # soonest expiry
take = min(g.remaining, amount)
g.remaining -= take
amount -= take
if g.remaining == 0:
heapq.heappop(live)
The order of the two halves matters. The total is checked before any grant is changed, so a rejected spend leaves the ledger exactly as it was.
When events arrive out of order
Look at Ana’s stage-2 row. G2 arrives after the t=10 spend was processed, but it happened before it. If G2 had been there at t=10, the spend would have used it, because it expires sooner. So a late grant changes which credits an earlier spend used, and that changes what expires later. You can’t fix this by pushing G2 onto the heap; the earlier choice is already baked in.
The fix is to change the model. Store each user’s events sorted by (at, kind, seq): time, then grants before
spends, then arrival order. Derive every answer by replaying them. To accept an event, insert it into a copy of the
log, replay everything, and keep the copy only if every spend, old or new, is still funded. balance(user, at)
then answers questions about the past too.
Say it like this: “Here’s a test the old design fails: a grant that arrives late but happened before a spend. I’ll change the design until it passes.”
Later stages
Now promotional credits must be spent before paid ones. Give each grant a tier (promo or paid) and put the
spending order in one function, for example (tier, expires_at, seq). There is one trap. Once the heap is ordered by tier first, its top is no longer the soonest-expiring grant,
so “pop expired grants from the top” stops working. Skip expired grants wherever they surface instead. That is safe
because replay applies spends in time order: a grant expired for one spend is expired for every later one. A rule
like that, which the code depends on, is called an invariant; say it out loud.
A “credits expired unused” report is four lines. Replay never consumes an expired grant, so what a grant holds after replaying to the window’s end is what it held when it expired.
What it costs
The family walkthrough has every stage as tested code, plus a differential test: a slow, obvious second implementation (an oracle) and a loop that checks both agree on thousands of random histories. It also measures the cost of replaying. As written, each event replays the log and each spend sums every grant, so the work per event grows with the history. Doubling the events from 250 to 500 made it about 6.5× slower in a run on 2026-10-12. A running total plus an append-only fast path made it linear.
The arithmetic behind the numbers (for a Staff-level follow-up)
- Let n be one user’s events and g their grants. Replay-on-every-event costs O(n × g) per event.
- Run on an Apple M1 Ultra (Python 3.13.7, 2026-10-12): 250 events took 0.044 s and 500 took 0.284 s. 0.284 ÷ 0.044 ≈ 6.5. Linear code would be 2× slower for 2× the events, quadratic 4×.
- A running total of unexpired credits makes the “is there enough?” check O(1). An append fast path applies an in-order event to cached state, so only late events pay for a full replay.
Senior vs Staff
Credit ledger
Senior
- Green stage 1 with tests fast; replays a sorted log for late events; states complexity.
Staff
- Raises late events, ties and the expiry instant before being asked, cuts scope with the interviewer on the long follow-up, and says how it would really be stored (append-only table, idempotency keys, a locked balance row).
Small-team version
This is the code a small company needs for usage-based pricing of an AI feature. Customers get monthly and promotional credits that expire, and every call to a language model spends some.
In production, don’t keep it in memory. Put it in the Postgres you already run as an append-only events table. Give each event a unique idempotency key: an id the caller sends, so a retried request with the same id is recognised and can’t spend twice. Do each spend in one transaction that locks the user’s balance row, checks it, and writes the event.
Before building any of it, check whether your billing provider already supports expiring credit grants. If it does, buy that: your code shrinks to sending usage events and reconciling. What you still own either way: the rules (order, expiry, overdraft) and the tests that pin them down.
Pitfalls
- Changing grants before checking the total. A rejected spend then leaves a half-spent ledger.
- Reading the wall clock inside the ledger. Expiry becomes untestable, and “balance yesterday” becomes impossible.
- Patching the heap for late events. A late event changes the model, not just one entry; replay is the honest fix.
- Floats for credits. Rounding errors make balances disagree by tiny amounts that tests catch and humans can’t explain.
- Saving all testing for the end. Hello Interview lists test coverage among OpenAI’s stated criteria (Hello Interview).
Go deeper
- Family walkthrough: Multi-part practical coding, especially its staged solution and the complexity section.
- Lazy expiry in a real cache, and why its clock read hurts tests: Build Your Own In-Memory Cache (Redis-lite)Not an LLM lab.
- The same “one rule in one function” habit on a graph: the task-manager card.