What they’re really asking
If you only remember one thing, say this in the first minute: “I’ll write a small interpreter, and at each step record the full state: the instruction pointer and every register. A deterministic machine with finite state must either halt or revisit a state, and the first revisited state is where the loop starts. So I store each state with the step I first saw it, and when one comes back, I return the loop’s start and length. I’ll add a step budget in case registers can grow forever.”
The rest of this page explains each part of that answer.
You get a list of instructions, like a tiny assembly language, and you run them. At some point the program either stops or starts doing the same thing over and over. Your job is to say where the repeating starts.
The coding is easy. The trap is the word “repeat”. Coming back to the same instruction is not the same as repeating. A countdown loop visits the same instructions many times, but the counter is different each time, so it is making progress and will stop. A real repeat means the whole state is the same as before. Then, because each step depends only on the state, everything after it repeats forever.
(A Sr Staff candidate’s Anthropic coding round was to “simulate a list of instructions and detect where execution starts repeating”; “I had a few bugs early on but finished around the 50-minute mark”, and “This round felt okay” Blind. The poster blames a different round for the outcome.) So the bar is a correct, debugged simulator in under an hour, with a sound definition of “repeat”.
Words you need first
- Program counter (pc): the index of the next instruction to run.
- Register: a named variable the program reads and writes. Here there is one, called
acc(accumulator). - State: everything the next step depends on. Here, the pc plus all registers.
- Deterministic: the same state always leads to the same next state.
- Step budget: a maximum number of steps, after which you stop and report that no repeat was found.
Clarify first
- Instruction set: which ops exist, and what does each do to the program counter and registers? Write them down as a table before coding.
- State: is it just the program counter, or registers and memory too? This is the key question. If a register changes every lap, revisiting an instruction is not a repeat.
- Output: the step where the loop starts, the loop length, or the instruction index?
- Termination: what does running off the end of the program mean? (Usually: the program halts.)
- Limits: can registers grow without bound? Then the program may run forever without repeating, and you need a step budget.
Say it like this: “When you say ‘starts repeating’, do you mean the same instruction again, or the same instruction with the same register values?”
Answer
The instruction set used here
| Op | What it does |
|---|---|
add n | add n to acc, then go to the next instruction |
jmp n | jump n instructions forward (negative means back) |
jnz n | if acc is not zero, jump n; otherwise go to the next instruction |
The example to follow
A countdown that ends in a tight loop. acc starts at 2:
0: add -1
1: jnz -1 (if acc != 0, go back to 0)
2: jmp 0 (jump to itself, forever)
Trace it one step at a time:
| Step | pc | acc before | What happens | What to say in the interview |
|---|---|---|---|---|
| 0 | 0 | 2 | acc becomes 1 | ”Record state (0, acc=2).“ |
| 1 | 1 | 1 | acc ≠ 0, jump back to 0 | |
| 2 | 0 | 1 | acc becomes 0 | ”pc 0 again, but acc is 1, not 2. Not a repeat.” |
| 3 | 1 | 0 | acc = 0, fall through to 2 | ”The countdown finished; that was progress.” |
| 4 | 2 | 0 | jump to itself | ”Record state (2, acc=0).“ |
| 5 | 2 | 0 | — | “Same full state as step 4: loop starts at step 4, length 1.” |
If you hashed only the program counter, you would report a loop at step 2, which is wrong: the program was
counting down and would have moved on. Running the code below on this program returns ("loop", 4, 1)
(run on 2026-10-12).
The code
Store each state with the step you first saw it. The first state you see twice is where the loop starts, and the gap between the two steps is its length.
def run_until_repeat(program, regs=None, max_steps=1_000_000):
"""program: list of (op, arg). Returns ('halt', step, regs) or ('loop', mu, lam)."""
pc, regs, seen = 0, dict(regs or {"acc": 0}), {}
for step in range(max_steps):
if not 0 <= pc < len(program):
return ("halt", step, regs)
state = (pc, tuple(sorted(regs.items())))
if state in seen:
return ("loop", seen[state], step - seen[state]) # loop start, loop length
seen[state] = step
op, arg = program[pc]
if op == "add":
regs["acc"] += arg
elif op == "jmp":
pc += arg
continue
elif op == "jnz":
if regs["acc"]:
pc += arg
continue
pc += 1
raise RuntimeError("step budget exhausted without a repeat")
A few details to point out as you write. The state is a tuple, so it can be a dictionary key. Jumps use
continue so they don’t also do pc += 1, which is the most common off-by-one in this problem. Running off
either end of the program is a halt. Time and memory are both O(steps).
Tests: a program that halts, a tight loop, and a loop where the accumulator goes up and back down within one lap, so the program counter repeats before the state does. They passed when run on 2026-10-12.
Why “halt or repeat” is guaranteed
Say it like this: “A deterministic machine with finite state must either halt or revisit a state, and the first revisited state is where the loop starts. So the state I hash has to be everything the next step depends on.”
The reason is counting: if there are only S possible states, then within S + 1 steps some state must appear twice. If a register is unbounded, there are infinitely many states, the program can run forever without repeating, and the step budget is what stops you.
Variants to expect
- “Infinite loop” check: if the interviewer only cares about the program counter (each instruction may run
once), the state is just
pcand memory is O(program length). - Too many states to store: use Floyd’s or Brent’s cycle detection. Both walk the sequence of states with two pointers moving at different speeds and need O(1) memory, at the cost of running the machine more than once.
- A likely next part: change one instruction so the program terminates. Try each candidate change and rerun, O(program length × steps).
Senior vs Staff
Simulation with repeat detection
Senior
- Clean interpreter, correct state definition, loop start and length, tests including the register case.
Staff
- Says why finite state guarantees halt-or-repeat and what breaks it (unbounded registers), offers Floyd/Brent for memory, and keeps the interpreter separate from detection so new ops are one line.
Small-team version
Interview-only as code. But the idea reappears in AI agents: programs where a language model decides, step by step, which tool to call next (search, run code, read a file). An agent that calls the same tool with the same arguments and gets the same result is in a loop. Detecting a repeated (tool, arguments) state is a cheap stop condition, alongside a step cap and a cost cap.
It pays for itself, because each agent step resends the whole conversation so far (the context) to the model, and you pay per input token (a token is roughly ¾ of a word). The context grows every step, so a stuck agent gets more expensive the longer it runs. With assumed sizes, stopping a stuck run at step 2 instead of a 20-step cap saves about 382,500 input tokens, about $0.77 per stuck run.
The arithmetic behind the numbers (for a Staff-level follow-up)
- Tokens sent over N steps: N × C0 + Δ × N(N + 1) ÷ 2, where C0 is the starting context and Δ the tokens added per step.
- Assumed: C0 = 4,000 tokens and Δ = 1,500 tokens per step.
- Stop at step 2: 2 × 4,000 + 1,500 × 3 = 12,500 tokens.
- Run to a 20-step cap: 20 × 4,000 + 1,500 × 210 = 395,000 tokens.
- Saved: 395,000 − 12,500 = 382,500 tokens. At Claude Sonnet 5’s $2 per million input tokens (list price on Anthropic’s pricing page, fetched 2026-10-11), about $0.77.
Pitfalls
- Hashing only the program counter when registers matter. A countdown then looks like a loop.
- Off-by-one on jumps. Doing
pc += argand then alsopc += 1. - No step budget for machines with unbounded state. The program may never repeat or halt.
- Mixing the interpreter and the detection logic. Each new op then means touching both.
Go deeper
- Family walkthrough: Short DSA screens with an infrastructure flavor.
- Cycle detection on a graph instead of a state machine: infra-102.
- Longer multi-part problems of the same kind: Multi-part practical coding.