The prompt
If you only remember one thing, say this in the first minute: “I’ll write my assumptions down first, then build the smallest correct version with a few tests, and only then take the next requirement. I’ll keep each rule (which credits get spent first, when a credit expires, what happens on overdraft) in exactly one function, and I’ll pass the time into every method instead of reading the clock. That way, when you change a rule, I change one function and rerun the tests. When a change is big, I’ll ask you which part matters most.”
The rest of this page explains each part of that answer, and shows it working on one problem from start to finish.
How this round differs from a LeetCode round
A normal algorithm interview gives you one puzzle with a fixed statement. You find the trick, write 30 lines, and you are done. The problem never changes under you.
A multi-part practical coding round is different in three ways:
- The problem is ordinary, and there is a lot of it. You build a small working system: a credit ledger, a spreadsheet, a task manager, a scheduler. No single step is clever. The difficulty is writing a few hundred correct lines in 60 to 90 minutes.
- The requirements change while you type. The interviewer adds a rule every so often (every 15 to 20 minutes in the practice staging on this page). Your first design either absorbs the change in a few lines or forces a rewrite you don’t have time for.
- Tests decide whether you passed. In some formats the interviewer watches you run code. In others an automatic grader runs edge-case tests you never see. Either way, code that “looks right” earns little.
So the skill being tested is not one algorithm. It is a habit: build a small correct core, prove it with a test, then extend it without breaking what already works. This page calls that habit the loop (core, test, extend).
The problem worked on this page
The version worked here is the credit ledger, because it shows every kind of change in a small space. Users receive credits that expire. They spend credits. You report balances. Then the rules change: events arrive out of order, promotional credits must be spent before paid ones, and finance wants a report of credits that expired unused.
Words you need first
- A grant gives a user some credits that expire at a set time. “Grant 100 credits at t=0, expiring at t=50.”
- A spend uses some of a user’s credits at a given time. If the user doesn’t have enough, the spend is an overdraft.
- The balance at time t is the total of all credits that are still unexpired and unspent at t.
- An event is one grant or one spend, with its timestamp. The ledger’s whole history is a list of events.
- Replay means rebuilding the state by applying the events again, in time order, from the beginning. It is the same idea as rebuilding a database from its write-ahead log.
Where this round was reported, in one line: Hello Interview’s OpenAI guide says live rounds “often focus on practical implementation”, naming “small databases, credit-tracking services, and resumable iterators”, each with “several behaviors to implement” (Hello Interview), and a question list on Aced (a site that aggregates reported questions) tags OpenAI with “Given credit issuance and usage events with expiry, compute the user’s remaining credit pool” (Aced (formerly Exponent)).
Implement a credit ledger where credits expire; requirements change as the problem goes on.
Staff signal A Staff candidate called the coding question "rather long" and advised using the interviewer to focus on the important parts.
Build a resumable iterator: one that can stop, keep its position, and continue later.
- Hello Interview 2026
Build a scheduler class whose requirements keep changing over a 90-minute CoderPad session.
"Design spreadsheet" as a long, multi-part coding problem; another report puts it at LeetCode medium or harder.
Staff signal A Senior candidate was rejected at this stage. Practice multi-part problems under time pressure in your own language.
Traverse spreadsheet cell dependencies and detect cycles.
Implement an in-memory task manager for an AI workflow system, with task dependencies and failure handling.
Convert a stream of sampled stack traces from a profiler into an execution trace of function start and end events. A follow-up changes one of the constraints.
Staff signal Rejected Anthropic candidates point to unfinished follow-ups, not wrong first answers. Get a correct version running quickly; expect the follow-up to change a constraint.
Given profiler start and end events, find the slowest code. Handle recursion cycles and functions that never return.
Object-oriented design screen: design a deck of cards.
- TechPrep Jul 2025
The other problems in this family
Each of these is a different costume on the same loop. The answer cards linked above work each one.
- Spreadsheet. Cells hold numbers or formulas that read other cells. Change one cell and every cell that depends on it must update; a formula that reads itself, directly or through other cells, is a cycle and must be rejected. A Harvey Senior candidate got “Design spreadsheet” with “multiple parts and follow ups” and was rejected (Aced). Another Harvey Senior report calls its screen a “Difficult, multi-part problem”, “at least a LeetCode medium” (Taro). An Aced Sierra list has traversing cell dependencies and detecting circular references (Aced (formerly Exponent)). A 2026 Harvey AI Agent candidate “had practiced the phone-screen problem many times. It was the Google Sheets problem, and I finished it immediately” (PracHub).
- Task manager. Tasks depend on other tasks; when one fails, everything that waits on it fails too. PracHub (another question-collecting site) lists a Perplexity technical screen titled “Implement Task Dependencies and Failure” (PracHub). Only the title is candidate-reported; the requirement list is PracHub’s write-up.
- Profiler traces. A profiler records which functions were running; you turn its raw output into “function X started at t1 and ended at t2”. An Anthropic Senior/Staff candidate’s phone screen asked how to convert stack samples to a trace, then: “Assume one of the original restrictions is removed” (Aced). A Staff candidate got profiler start and end events, and the interviewer “started breaking it with edge cases like cycles, infinite loops, and functions that never return” (Aced).
- Scheduler. A class that runs tasks at given times. A Glassdoor search snippet describes an OpenAI scheduler class whose requirements kept changing over a 90-minute CoderPad session (a shared online code editor) (Glassdoor, snippet only, low confidence).
- Deck of cards. A small object design: shuffle, deal, sort. A Scale AI candidate’s round was “to implement methods based on a deck of cards, shuffling, dealing, sorting and viewing the cards”, and “Speed was definitely important” (TechPrep).
None of these sources gives the exact sequence of follow-ups. The four ledger stages below are a plausible staging built for practice, not a transcript of any company’s question.
What is being tested
Four things, in roughly the order interviewers notice them.
Working code in volume. Hello Interview puts the difficulty in “the amount of working code you need to produce within the session”, and relays an OpenAI Staff candidate: “The coding problem question was rather long, use the interviewer to focus on important parts” (Hello Interview). The same guide lists OpenAI’s criteria as solution design, code quality, performance and test coverage. It says candidates report CoderPad, a shared browser editor where you can run code and tests, so the interviewer sees whether you run things early.
Speed. Candidates say this plainly. The Harvey Senior candidate: “You need to be really fast at coding”, and “practicing coding in your own language is really important” (Aced). A Harvey SWE II candidate: “The problems weren’t hard, but the pacing is an issue”, and “Expectations for speed versus talking through were unclear” (Taro). Neither rejection came with a stated reason, so read these as the candidates’ own lessons, not as interviewer feedback.
Surviving the follow-up. The second half of the problem is where reports put the weight. The Anthropic stack-sample candidate “didn’t finish that part” (the variant with a restriction removed) but kept talking through the approach and passed the screen (Aced). The profiler candidate wrote: “I wasn’t proactively naming all those failure modes the way they’d expect at staff level” (Aced). Say it like this when a follow-up lands: “Before I change code, the first version assumed X. This requirement removes X, so the function that relied on it is the one I’ll change.”
Edge cases checked by tests you can’t see. Anthropic’s online assessment runs on CodeSignal, a platform where the task is split into levels and an automatic grader runs tests against your code. A 2024 commenter on Blind (an anonymous forum for tech employees) said the grader seemed to focus on speed and “passing a bunch of edge case tests”; another “finished the test in 65mins out of 90” (Blind). interviewing.io quotes an engineer: “There were four levels”, the spec “would get more complicated at each level, and your code had to pass all the tests at one level”, “All in two hours” (interviewing.io). The two time limits disagree; ask your recruiter.
Why companies use this format
interviewing.io found that verbatim and lightly modified LeetCode questions were easy to cheat on with ChatGPT, and “Only fully custom questions were largely impervious to cheating” (interviewing.io). A long custom problem with a moving spec is one answer to that. As early as March 2025, Hello Interview grouped Stripe, Coinbase, OpenAI and Airbnb as using tasks “like designing a query engine, implementing a key-value store, or designing an in-memory database to handle transactions” (Hello Interview (Substack)).
AI tools
Usually banned in this round. Anthropic’s guidance is no AI in live interviews or take-homes unless Anthropic says otherwise (Anthropic). Hello Interview tells OpenAI candidates to assume no AI in live coding and to turn off autocomplete when practising (Hello Interview). Practise this family with your own hands.
Clarify and scope
For the ledger, each of these questions changes the code. Ask them in the first five minutes, write the answers as a comment block at the top of the file, and move on. The comment block lets the interviewer correct a wrong assumption in one glance.
- Expiry boundary. Is a credit usable at the exact instant it expires? Assume not: a credit is usable while
t < expires_at. This is called an exclusive (or half-open) boundary. - Which credits does a spend use? Soonest expiry first is the natural default, because it wastes the least. Ask anyway, because stage 3 will change it.
- Overdraft. If a spend is larger than the balance, reject it whole or take what is there? Assume reject, and leave the state exactly as it was.
- Time order. Do events arrive in timestamp order? Assume yes for now, and say you expect this to change. That remark earns credit when it does.
- 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.
- Scale. How many events per user? Assume thousands in the interview; the performance section returns to this.
Out of scope unless asked: saving to disk, many threads at once, multiple currencies, and refunds. Name them once so the interviewer knows you saw them.
Say it like this: “I’ll assume exclusive expiry, soonest-expiry-first, reject-on-overdraft, in-order events, and integers. I’ve written those at the top. Stop me if any is wrong.”
Plan before code
The shape of the code
Here is the structure you are aiming for. It looks like a tiny database, which is not an accident.
caller / test harness
│ grant(user, amount, at, expires_at)
│ spend(user, amount, at)
│ balance(user, at) expired(user, start, end)
▼
┌──────────────────────────────┐
│ Public methods │ validate input first; never read the clock
└──────────────┬───────────────┘
│ one event per call
▼
┌──────────────────────────────┐
│ Event log per user │ sorted by (time, grant-before-spend, arrival)
└──────────────┬───────────────┘
│ replay in time order
▼
┌──────────────────────────────┐
│ Consume rule (one function) │ which grant pays next; skip expired ones;
│ │ reject the whole spend if it can't be paid
└──────────────┬───────────────┘
▼
per-grant remaining amounts → balance, reports
Public methods. One method per behavior, with validation at the top. The interviewer’s harness will call
these, so match their names and argument order exactly. Every method takes the time at as an argument.
Event log. Stage 1 doesn’t need it; stage 2 does. Each user’s events are kept sorted by time. This is the source of truth, in the same way a write-ahead log is the source of truth for a database.
Consume rule. The single function that decides which grant pays for a spend. When the interviewer changes the spending order, this is the only function you touch.
Results. Balances and reports are derived from the per-grant remaining amounts after replay. Nothing is stored twice, so nothing can disagree.
Three habits that keep the next change small
- One public method per behavior, with validation at the top:
grant,spend,balance. - One function owns each rule. The consumption order, the expiry check and the overdraft check each live in one place. When a rule changes, you change one function.
- Inject time. Every method takes
at; nothing reads the wall clock. That makes every test exact, and it makes “what was the balance yesterday?” possible later. Code that callstime.time()inside can only be tested with sleeps.
One user through all four stages
This is the worked example for the rest of the page. One user, Ana, and a short history. Each row is a new event or a new rule, and the balances were checked by running the 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 credits at t=0, expiring at t=50 (call it G1) | balance 100 | ”One heap per user, ordered by expiry.” |
| 1 | Spend 60 at t=10 | taken from G1; balance at t=10 is 40 | ”I 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, which expires sooner; balance at t=10 is 140, at t=25 is 100 (40 of G2 expired unused) | “A late event changes which credits an earlier spend used. I can’t patch that. I’ll store the events and replay them.” |
| 3 | New rule: promotional credits are spent before paid ones. Grant 20 promo credits at t=30, expiring at t=60 (G3); spend 50 at t=35 | the spend takes all 20 promo credits first, then 30 from G1; balance at t=35 is 70 | ”Only the ordering function changes. Without this rule, the spend would have used G1 first because it expires sooner.” |
| 3 | A late spend of 90 at t=32 arrives | rejected: it would leave the t=35 spend unfunded | ”Accepting it would rewrite history. Rejecting is my default; it’s a product decision, so I’d ask.” |
| 4 | Report: credits that expired unused, in the window [0, 61) | G2 lost 40 at t=20, G1 lost 70 at t=50, G3 lost 0: total 110 | ”This report is four lines, because replay already knows what each grant held when it expired.” |
Keep this table in mind. Each stage below adds exactly one row’s worth of behavior.
Pacing for 60 to 90 minutes
| Minutes (90-min round) | 60-min round | What | Done when |
|---|---|---|---|
| 0–7 | 0–5 | Clarify, write assumptions | the comment block exists |
| 7–25 | 5–18 | Stage 1 core + 4 tests | tests pass on the first run you show |
| 25–45 | 18–33 | Stage 2 (out-of-order) | late-grant and late-spend tests pass |
| 45–60 | 33–45 | Stage 3 (credit tiers) | tier test passes, earlier tests still pass |
| 60–75 | 45–55 | Stage 4 (report) | report test passes |
| 75–90 | 55–60 | Complexity, what you’d harden | you said it before being asked |
Two rules for the clock. If stage 1 isn’t green by about a quarter of the round, cut scope out loud: “I’ll support one user first and generalize after.” And when a follow-up is large, ask which part matters most; that is the OpenAI Staff candidate’s advice in practice (Hello Interview).
Solution in stages
All code below is Python 3.13. Each stage’s tests passed when run on 2026-10-12 (31 tests across the four versions, plus a 2,000-case random test against a slow reference implementation, described under Verification).
Stage 1: grants, spends, balance
A min-heap is a structure that always hands you its smallest item in O(log n) time. Keep one per user, ordered by expiry, and its top is always the next credit to spend. When a grant has expired, don’t hunt for it; drop it the next time it reaches the top. This is called lazy expiry, and it is the same trick a cache with a TTL uses.
import heapq
import itertools
from dataclasses import dataclass
class InsufficientCredits(Exception):
pass
@dataclass
class Grant:
grant_id: int
remaining: int
expires_at: int # exclusive: a credit is usable while t < expires_at
class Ledger:
def __init__(self):
self._heaps = {} # user -> min-heap of (expires_at, grant_id, Grant)
self._last = {} # user -> time of the last event (stage-1 assumption)
self._ids = itertools.count(1)
def grant(self, user, amount, at, expires_at):
if amount <= 0 or expires_at <= at:
raise ValueError("amount must be > 0 and expiry after the grant time")
self._advance(user, at)
g = Grant(next(self._ids), amount, expires_at)
heapq.heappush(self._heaps.setdefault(user, []), (expires_at, g.grant_id, g))
return g.grant_id
def spend(self, user, amount, at):
if amount <= 0:
raise ValueError("amount must be > 0")
self._advance(user, at)
live = self._live(user, at)
if sum(g.remaining for _, _, g in live) < amount:
raise InsufficientCredits(f"{user}: wants {amount}") # nothing changed
while amount: # soonest expiry first
_, _, g = live[0]
take = min(g.remaining, amount)
g.remaining -= take
amount -= take
if g.remaining == 0:
heapq.heappop(live)
def balance(self, user, at):
return sum(g.remaining for _, _, g in self._live(user, at))
def _live(self, user, at):
heap = self._heaps.get(user, [])
while heap and heap[0][0] <= at: # lazy expiry: drop grants that are past it
heapq.heappop(heap)
return heap
def _advance(self, user, at):
if at < self._last.get(user, at):
raise ValueError("events must arrive in time order")
self._last[user] = at
Two details to point out while you type. The overdraft check runs before any change, so a rejected spend leaves
the ledger exactly as it was. And the heap entries are tuples (expires_at, grant_id, g): when two grants expire at
the same time, Python compares the next field, and because grant_id is unique it never has to compare two
Grant objects (which would raise an error).
def test_soonest_expiry_spent_first():
L = Ledger()
L.grant("u", 100, at=0, expires_at=50)
L.grant("u", 100, at=0, expires_at=20)
L.spend("u", 150, at=10) # 100 from the t=20 grant, 50 from the t=50 grant
assert L.balance("u", at=10) == 50
assert L.balance("u", at=50) == 0 # expiry is exclusive
def test_overdraft_rejected_and_nothing_changes():
L = Ledger()
L.grant("u", 30, at=0, expires_at=100)
with pytest.raises(InsufficientCredits):
L.spend("u", 31, at=5)
assert L.balance("u", at=5) == 30
In Ana’s story, stage 1 handles the first two rows: grant 100, spend 60, balance 40.
Stage 2: events arrive out of order
The new requirement breaks stage 1’s model, and it is worth seeing why before typing. Look at Ana’s third row. The grant G2 arrives after the t=10 spend was processed, but it happened before it. If it had been there at t=10, the spend would have used G2 (it expires sooner), not G1. So the late event changes which credits an earlier spend used, and therefore changes what expires later. Pushing G2 onto the heap can’t undo the choice already made. The state is a function of the whole history, sorted by time.
So store each user’s events sorted by time, and compute answers by replaying them. The consumption rule is the stage-1 loop, moved into its own function. Accepting an event now means three steps: insert it in time order, replay everything, and keep it only if every spend, old or new, is still funded.
import bisect
from dataclasses import dataclass, field
GRANT, SPEND = 0, 1 # at the same timestamp, grants apply before spends
@dataclass(frozen=True, order=True)
class Event:
at: int
kind: int
seq: int # arrival order breaks the last ties
amount: int = field(compare=False)
expires_at: int = field(compare=False, default=0)
class Ledger:
def __init__(self):
self._log = {} # user -> list[Event], sorted
self._seq = itertools.count(1)
def grant(self, user, amount, at, expires_at):
if amount <= 0 or expires_at <= at:
raise ValueError("amount must be > 0 and expiry after the grant time")
return self._add(user, Event(at, GRANT, next(self._seq), amount, expires_at))
def spend(self, user, amount, at):
if amount <= 0:
raise ValueError("amount must be > 0")
return self._add(user, Event(at, SPEND, next(self._seq), amount))
def balance(self, user, at):
grants = _replay(self._log.get(user, []), until=at)
return sum(rem for exp, rem in grants.values() if exp > at)
def _add(self, user, event):
log = self._log.get(user, [])
i = bisect.bisect(log, event)
candidate = log[:i] + [event] + log[i:]
_replay(candidate, until=float("inf")) # raises if any spend, old or new, fails
self._log[user] = candidate # only now is the event accepted
return event.seq
def _replay(events, until):
"""Apply events with at <= until in order. Returns {seq: [expires_at, remaining]}."""
grants, heap = {}, [] # heap: (expires_at, seq) of non-empty grants
for e in events:
if e.at > until:
break
if e.kind == GRANT:
grants[e.seq] = [e.expires_at, e.amount]
heapq.heappush(heap, (e.expires_at, e.seq))
else:
_consume(grants, heap, e.amount, e.at)
return grants
def _consume(grants, heap, amount, at):
while heap and heap[0][0] <= at: # expired before this spend
heapq.heappop(heap)
if sum(grants[s][1] for _, s in heap) < amount:
raise InsufficientCredits(f"wants {amount} at t={at}")
while amount:
_, s = heap[0]
take = min(grants[s][1], amount)
grants[s][1] -= take
amount -= take
if grants[s][1] == 0:
heapq.heappop(heap)
Notice the pattern in _add: build a candidate log, test it by replaying, and only then swap it in. If the replay
raises, the real log was never touched. This is the “check, then commit” rule from stage 1, applied to the whole
history.
Two decisions to say out loud. First, a late spend that would leave an already-accepted later spend unfunded is
rejected (Ana’s late spend of 90 at t=32). The alternative, accepting it and marking the later spend as
overdrawn, is a product decision, so ask. Second, balance(user, at) now answers questions about the past for
free, which the interviewer may not have asked for yet.
def test_late_grant_changes_which_credits_were_used():
L = Ledger()
L.grant("u", 100, at=0, expires_at=50)
L.spend("u", 60, at=10)
L.grant("u", 100, at=5, expires_at=20) # arrives late, but happened before the spend
assert L.balance("u", at=10) == 140 # the spend now drew on the t=20 grant
assert L.balance("u", at=25) == 100 # 40 left of it expired at t=20
def test_late_spend_that_breaks_history_is_rejected():
L = Ledger()
L.grant("u", 100, at=0, expires_at=50)
L.spend("u", 80, at=20)
with pytest.raises(InsufficientCredits):
L.spend("u", 30, at=10) # would leave the t=20 spend unfunded
assert L.balance("u", at=30) == 20
The first test is Ana’s stage-2 row, and it is the one to write before the code. It fails on stage 1’s design and passes on stage 2’s, which shows the interviewer you understood what the requirement changed. Say it like this: “Here’s a test that the old design fails. Now I’ll change the design until it passes.”
Stage 3: promotional credits first
Now promotional credits are spent before paid ones, even when a paid grant expires sooner. Each grant gets a tier: promo or paid. If the consumption order lives in one function, this is a small change: the heap is now ordered by tier first, then expiry.
There is one catch, and it is the bug most people write here. Once the heap is ordered by tier first, its top is no longer the soonest-expiring grant. The stage-2 loop “pop expired grants from the top” stops working, because an expired paid grant can sit below an unexpired promo grant and never reach the top. The fix: skip expired grants wherever they surface, and check whether the spend can be paid by summing unexpired grants directly.
PROMO, PAID = 0, 1 # lower tier is spent first
# Event gains: tier: int = field(compare=False, default=PAID); grant() takes tier=PAID
def _order(e):
"""The one place that decides which credits a spend uses first."""
return (e.tier, e.expires_at, e.seq)
def _replay(events, until):
grants, heap = {}, []
for e in events:
if e.at > until:
break
if e.kind == GRANT:
grants[e.seq] = [e.expires_at, e.amount]
heapq.heappush(heap, (_order(e), e.seq))
else:
_consume(grants, heap, e.amount, e.at)
return grants
def _consume(grants, heap, amount, at):
if sum(rem for exp, rem in grants.values() if exp > at) < amount:
raise InsufficientCredits(f"wants {amount} at t={at}")
while amount:
key, s = heapq.heappop(heap)
exp, rem = grants[s]
if exp <= at: # expired; spends replay in time order, so drop it for good
continue
take = min(rem, amount)
grants[s][1] -= take
amount -= take
if grants[s][1]:
heapq.heappush(heap, (key, s))
Dropping an expired grant for good is safe only because replay applies spends in time order: once a grant is expired for the spend at t=35, it is expired for every later spend too. Say that sentence. A rule the code relies on and that must stay true is called an invariant, and naming it is what interviewers listen for.
In Ana’s story, the t=35 spend of 50 now takes all 20 promo credits from G3 first, then 30 from G1, leaving a balance of 70.
Stage 4: credits that expired unused
Finance wants to know how much credit expired unused in a time window. This is called breakage: credit a
customer paid for or was given but never used. Because replay never consumes an expired grant, each grant’s
remaining amount after replaying up to end is exactly what it held when it expired.
def expired(self, user, start, end):
"""Credits that expired unused with start <= expires_at < end."""
grants = _replay(self._log.get(user, []), until=end)
return sum(rem for exp, rem in grants.values() if start <= exp < end)
def test_expired_report():
L = Ledger()
L.grant("u", 50, at=0, expires_at=10)
L.grant("u", 50, at=0, expires_at=30)
L.spend("u", 70, at=5) # 50 + 20
assert L.expired("u", start=0, end=31) == 30
assert L.expired("u", start=0, end=30) == 0
For Ana, the window [0, 61) gives 40 (from G2) plus 70 (from G1) plus 0 (from G3) = 110.
Stage 4 took four lines because stages 2 and 3 kept the state derivable from the log. That is the payoff of the skeleton, and it is the point to make when the interviewer asks what you would do differently.
Verification
Unit tests prove the cases you thought of. For a ledger, also write a differential test. You write a second, slow and obvious implementation of the same rules (list scans, no heaps, full recompute on every call). This second version is called an oracle, because you trust its answers. Then a loop throws random histories at both and checks that they always agree. Any disagreement is a bug in one of them, and the failing case number tells you which history to look at.
The oracle used here sorts usable grants by (tier, expires_at, seq) on every spend and recomputes everything from
scratch, so it shares the rules but not the data structures. That matters: if the oracle used the same heap trick,
it would share the same heap bug.
def test_matches_oracle_on_random_histories():
rng = random.Random(7)
for case in range(2000):
L, O = Ledger(), Oracle()
for _ in range(rng.randint(1, 25)):
user, at = rng.choice("ab"), rng.randint(0, 40)
if rng.random() < 0.45:
amt, exp, tier = rng.randint(1, 30), at + rng.randint(1, 30), rng.choice([PROMO, PAID])
assert O.add(user, (at, 0, amt, exp, tier))
L.grant(user, amt, at, exp, tier)
else:
amt = rng.randint(1, 40)
ok = O.add(user, (at, 1, amt, 0, PAID))
try:
L.spend(user, amt, at)
assert ok, case
except InsufficientCredits:
assert not ok, case
for u in "ab":
t = rng.randint(0, 75)
assert L.balance(u, t) == O.balance(u, t), case
s, e = sorted(rng.sample(range(0, 80), 2))
assert L.expired(u, s, e) == O.expired(u, s, e), case
Timestamps are drawn at random, so most histories arrive out of order, and spends are large enough that about half
get rejected. The fixed seed (Random(7)) means a failure reproduces exactly on the next run. The test passed for
the stage-4 ledger and for the faster version below when run on 2026-10-12.
In an interview you won’t have time for the oracle at every stage. Write it once, at the stage where the logic gets subtle (here, stage 2), and say what it covers: “This compares my ledger with a dumb version on 2,000 random histories, most of them out of order.”
What to test at each stage (a practice checklist, not a list of any company’s tests):
| Stage | Tests |
|---|---|
| 1 | expiry order, exact expiry boundary, overdraft leaves state unchanged, users isolated, out-of-order rejected |
| 2 | late grant changes the earlier spend, late spend that breaks history is rejected, balance in the past |
| 3 | promo before paid even when paid expires sooner, an expired promo grant is skipped |
| 4 | report window boundaries (start inclusive, end exclusive) |
Complexity and performance
Start with what the cost means, then the numbers. Stage 1 does a small amount of work per event. Stages 2 to 4, as written, rebuild the whole history every time an event arrives. That is correct and simple, but the cost of each new event grows with the size of the history, so the total cost grows much faster than the number of events.
Let n be one user’s events and g their grants.
- Stage 1:
grantis O(log g).spendis O(g) for the “is there enough?” sum, plus O(k log g) for the k grants it touches.balanceis O(g). - Stages 2–4 as written: every accepted event replays the whole log, and every replayed spend sums over all grants. That is O(n × g) per event.
That second line matters more than it looks. In a run on an Apple M1 Ultra on 2026-10-12, doubling the events from 250 to 500 made the stage-4 ledger about 6.5× slower. Linear code would be 2× slower.
Two fixes bring it back:
- A running total. Keep a second heap ordered by expiry and a
livecounter of unexpired credits. Before each spend, pop grants whose expiry has passed and subtract what they still held. The “is there enough?” check becomes O(1). - An append fast path. Cache each user’s replay state after the whole log. An event that sorts after every
existing event (the common case) is applied to the cached state in O(k log g). Only a late event pays for a full
replay. One subtlety: if
applyrejects a spend after it has already expired grants up to the spend’s time, drop the cache, because a later in-order event may predate that spend.
def _add(self, user, event):
log = self._log.setdefault(user, [])
if not log or log[-1] < event: # in order: the common case
st = self._current(user)
try:
st.apply(event)
except InsufficientCredits:
del self._state[user] # apply() may have expired grants early
raise
log.append(event)
return event.seq
i = bisect.bisect(log, event) # late event: replay everything once
candidate = log[:i] + [event] + log[i:]
st = _replay(candidate)
self._log[user], self._state[user] = candidate, st
return event.seq
With both fixes, the same run grew linearly (about 0.1 s for 50,000 in-order events). With one event in fifty arriving late, it slowed again, because each late event still replays the log. If late events are common, the next step is a snapshot (a saved copy of the state) every K events, so a replay starts from the nearest snapshot before the late event instead of from the beginning.
The arithmetic behind the numbers (for a Staff-level follow-up)
All timings are single runs on one machine (Apple M1 Ultra, Python 3.13.7, 2026-10-12): useful for the shape of the curve, not as benchmarks.
- Slow version: 250 in-order events took 0.044 s and 500 took 0.284 s. 0.284 ÷ 0.044 ≈ 6.5× for 2× the events. Linear would be 2×; quadratic would be 4×. It is worse than quadratic because each event replays n events and each replayed spend sums over g grants, and both n and g grow with the history.
- Both fixes, in order: 500 / 5,000 / 50,000 events took 0.001 / 0.011 / 0.114 s. Each 10× in events is about 10× in time, which is linear.
- One event in fifty late: 5,000 events took 0.229 s, about 20× the 0.011 s of the all-in-order run, because each of the roughly 100 late events (5,000 ÷ 50) replays the log.
You don’t need to write the fast version in the round. You need to say what the slow version costs and which change fixes which term. Say it like this: “Replay-on-every-event is O(n × g) per event. A running total removes the g; an append fast path removes the n for in-order events. Late events still pay full price, and snapshots fix that if they’re common.”
Small-team version
You own AI features at a 50–500 person company with a few engineers and coding agents. Two things carry over from this family: the ledger itself, and the habit.
The ledger is real work
Usage-based pricing for an AI feature needs exactly this. Customers get monthly or promotional credits that expire. Each call to a language model spends some, priced by tokens (the chunks of text, roughly ¾ of a word each, that model providers bill by). And finance asks about breakage. The interview’s in-memory heap is the wrong storage for it.
- Build: an append-only
credit_eventstable in the Postgres you already run, with a unique idempotency key per event. That is an id the caller sends with each event, so a retried webhook carrying the same id is recognised and can’t spend twice. A spend is one transaction that locks the user’s row (SELECT … FOR UPDATE), checks the balance and inserts the event. The consumption order and expiry rules stay in one tested function, as in the interview. - Size it before choosing anything fancier. With assumed traffic of 2,000 paying customers making 500 metered calls a day each, you write about a million spend rows a day, roughly 37 GB a year. One Postgres instance handles that; you don’t need a stream processor or a separate ledger database.
- What the ledger is guarding. With an example request on gpt-5-mini, one call costs about $0.0011. A million calls a day is roughly $33,000 a month of model spend that the ledger bills back to customers. If 1% of usage events were counted twice after retries, customers would be overcharged about $330 a month, which is why the idempotency key comes before any performance work.
- Buy: invoicing, tax and payment collection, from your billing provider. Check whether it supports credit grants with expiry and a priority order before you build your own; if it does, your code shrinks to sending usage events and reconciling.
- Skip: replaying the full history on every request. Keep a stored balance per user, updated in the spend transaction, and use replay only for audits and the late-event path.
The arithmetic behind the numbers (for a Staff-level follow-up)
- Rows: 2,000 customers × 500 calls a day (assumed figures) = 1,000,000 spend rows a day. At an assumed 100 bytes per row including indexes, that is 0.1 GB a day, and 0.1 × 365 = 36.5, about 37 GB a year.
- Cost per call: the research-file example request (3,000 input tokens with 2,000 of them cached, 400 output tokens) on gpt-5-mini at its list price fetched 2026-10-11 ($0.25 input, $0.025 cached input, $2.00 output per 1M tokens): (1,000 × $0.25 + 2,000 × $0.025 + 400 × $2.00) ÷ 1,000,000 = $0.0011.
- Monthly spend: $0.0011 × 1,000,000 calls = $1,100 a day, about $33,000 a month. 1% double-counted is about $330 a month.
Revisit when spends per second for one customer get high enough that the row lock becomes a bottleneck (one large tenant’s batch job, for example), when finance needs revenue-recognition reports the event table can’t answer, or when a second product starts selling credits and the rules multiply.
The habit is the job
Elicit’s hiring manager described their AI-engineer coding round as a 60-minute exercise where the interviewers “play product manager” while the candidate changes “a little web app”, for example to “Convert a synchronous REST API to an asynchronous streaming endpoint” (Latent Space, 2024-06-21). PostHog’s paid SuperDay task is “designed to be too much work for one person to complete in a day”, to test prioritization (PostHog handbook, fetched 2026-10-12). Small companies test the same loop this family tests because it is the job: a requirement arrives half-specified, you ship a correct core, and the next change has to be cheap.
With coding agents doing most of the typing, what you still own is what the interview grades: the boundary rules (exclusive expiry, ties, overdraft), the test that shows a requirement changed the model (the late-grant test), and the invariant the code relies on (spends replay in time order).
How to practise
- Take the reported problems in this family (ledger, spreadsheet, task manager, resumable iterator, scheduler, stack samples to a trace, deck of cards) and write each one three times on a timer, in your interview language, without autocomplete.
- Split each into four stages before you start, or have an assistant write the stages and hide them from you until you finish the previous one.
- Track two numbers per attempt: minutes to a green stage 1, and how many earlier tests broke when a later stage landed. The second number is the one that measures structure.
- Do at least one run in CoderPad-style conditions (a single file, a run button, no IDE) and one in CodeSignal style, where tests decide the spec.
Senior vs Staff
Same ledger, different bar
Senior
- Gets stage 1 green quickly with tests, and keeps the consumption rule in one function.
- Handles out-of-order events correctly by replaying a sorted log, and says the late-spend policy is a product choice.
- States the complexity of what they wrote.
Staff
- Names the failure modes before the interviewer does: late events that invalidate history, ties, the exact expiry instant, rejected spends that leave half-updated state.
- Uses the interviewer to cut scope on the long follow-up, then explains the invariant the remaining code depends on.
- Says what the slow version costs, which change fixes which term, and how it would really be stored (append-only table, idempotency keys, a locked balance row).
The level difference shows up in the follow-ups. A Senior candidate handles each new rule well when it arrives. A Staff candidate raises the rule before it arrives. The Anthropic profiler candidate’s own reading of their weakest round was not naming failure modes “the way they’d expect at staff level” (Aced). At Staff, raise the cycles, the never-returning functions and the late events yourself.
Follow-ups
Reported (Anthropic, first-hand): one of the original restrictions is removed. Handle it efficiently.
The report doesn’t say which restriction (Aced). For the ledger, the analogue is stage 2: “events arrive in order” is removed. The method is the same either way: say which invariant the restriction was buying you, show the test that now fails, then change the one function that relied on it.
Reported (Anthropic, first-hand): edge cases like cycles, infinite loops and functions that never return.
From the profiler variant (Aced). The general answer: decide what the output should be for malformed input before writing code. For a ledger the equivalents are a spend with no grants, a grant that expires before it starts and an event for an unknown user. Reject, clamp or flag, and write the test.
Not reported; a natural next push: refund a spend.
Refunded credits go back to the grants they came from, so record which grants each spend drew on (a list of
(grant, amount) pairs from _consume). If a source grant has expired by the refund time, the policy is a
product question: restore with the original expiry (lost), or issue a fresh grant. Ask.
Not reported; a natural next push: make it thread-safe.
One lock per user is enough, because users are independent. Hold it across the check and the change in
_add; a global lock is correct but makes every user wait for every other. In a real service the database
row lock does this job.
Not reported; a natural next push: what if the same event is delivered twice?
Make callers send an idempotency key and store it with the event. A second event with the same key returns the first result instead of spending again. This matters more in production than any heap choice.
Reported title (Perplexity, PracHub): a task manager with dependencies and failure handling. How does the ledger skeleton carry over?
Same habits, different core: a graph instead of a heap. Store edges in both directions, pass a failure on to every task that depends on the failed one (directly or indirectly) with a breadth-first search, and check for a cycle before adding an edge. See the eng-062 card.
Common mistakes
- Starting with the general design. Designing for every future requirement costs the time you need for stage
- Write the simplest correct core, but put each rule in one function.
- No tests until the end. On CodeSignal-style rounds the tests define the spec; in CoderPad rounds the interviewer watches whether you run code early. Hello Interview lists test coverage among OpenAI’s criteria (Hello Interview).
- Changing state before validating. A spend that fails halfway through leaves a corrupted balance. Check, then change, or replay into a candidate and swap.
- Reading the wall clock.
time.time()inside the ledger makes expiry untestable and history impossible. - Fighting the follow-up instead of asking about it. When the follow-up is big, ask which part matters.
- Practising only with an assistant. In the companies most associated with this format, live rounds are reported as no-AI (Anthropic, Hello Interview), and speed is the most common lesson candidates report (Aced, Taro).
Prove it with a lab
No lab builds a credit ledger. These cover the pieces this family reuses. Two graph terms appear in the notes. A three-state DFS is a depth-first search that marks each node unvisited, on the current path, or finished; reaching a node that is on the current path means a cycle. Kahn’s algorithm orders a dependency graph by repeatedly taking nodes whose dependencies are all done.
Read dag.go: ValidateDAG is a three-state DFS that reports a cycle, TopoSort is Kahn's algorithm, and the parallel executor fails fast. That is the core of the spreadsheet recompute and the task manager. Its unknown-dependency error prints the stage name twice, a small bug worth fixing as practice.
A scheduler loop with missed-run backfill (Catchup). Compare it with the scheduler card: the lab scans every job for the earliest next run, where a heap gives O(log n), and it reads time.Now() directly, where an injected clock makes tests exact.
Not an LLM lab; used here only for lazy TTL expiry, the same idea as dropping expired grants when you next look. Its is_expired() calls Instant::now() inside the check: rewrite it to take the time as an argument and the tests stop depending on sleeps.
Not an LLM KV cache: this lab is a Redis-style key-value cache. Use llm-inference for attention KV caching.
Spans with start and end times and parent ids are the output shape of the profiler variants (infra-018, infra-019). The package doesn't compile as of 2026-10-11 (type errors in span.go), so read it for the data model, not as working code.
Partial: the code is real, but its tests don't pass yet (the Go package does not compile, as of 2026-10-11).
Questions in this family
9 reported questions share this underlying problem. 9 have an answer card. Each one links to its own page with sources and confidence.
- Implement an in-memory task manager for an AI workflow system, with task dependencies and failure handling.
- Traverse spreadsheet cell dependencies and detect cycles.
- "Design spreadsheet" as a long, multi-part coding problem; another report puts it at LeetCode medium or harder.
- Object-oriented design screen: design a deck of cards.
- Implement a credit ledger where credits expire; requirements change as the problem goes on.
- Build a resumable iterator: one that can stop, keep its position, and continue later.
- Convert a stream of sampled stack traces from a profiler into an execution trace of function start and end events. A follow-up changes one of the constraints.
- Given profiler start and end events, find the slowest code. Handle recursion cycles and functions that never return.
- Build a scheduler class whose requirements keep changing over a 90-minute CoderPad session.
Sources
- Hello Interview
- Aced (formerly Exponent)
- Aced
- Taro
- Taro
- PracHub
- Aced (formerly Exponent)
- PracHub
- TechPrep
- Aced
- Aced
- Glassdoor
- Blind
- interviewing.io
- interviewing.io
- Hello Interview (Substack)
- Anthropic
- Perplexity
- Canva Engineering
- How to Hire AI Engineers (Latent Space, 2024-06-21)
- PostHog handbook: hiring process (undated, fetched 2026-10-12)