AI Interviews · Question

Build a resumable iterator: one that can stop, keep its position, and continue later.

Practical coding question reported at OpenAI (2026). Sources, confidence and an answer card.

Researched · updated

eng-121 AI Engineer Classic DSA & object-oriented design Practical coding Staff+ Medium confidence
On this page

What they’re really asking

If you only remember one thing, say this in the first minute: “An iterator’s position is just data. I’ll write a class, not a generator, and keep the position as two plain numbers: which source I’m in and where I am inside it. get_state() returns those numbers, they survive a JSON round trip, and a new iterator built from them carries on exactly where the old one stopped. Later, if the data can change underneath, I’ll resume from a stable key instead of a position, and I’ll say the delivery guarantee is at-least-once unless processing is idempotent.”

The rest of this page explains each part of that answer.

A resumable iterator is one you can stop, save, and restart later, even in a new process, without repeating or skipping items. The interviewer wants to see that you treat “where am I?” as explicit data you own, small enough to save and plain enough to reload.

This is different from a normal iterator question. In everyday Python you write a generator with yield and never think about its position; Python keeps it hidden inside a paused function. That hidden position can’t be saved to a file or sent to another machine. So the moment the interviewer says “resume after a restart”, the usual tool stops working, and the question becomes: what is the smallest piece of data that says exactly where I am?

The problem is also staged. The first version is short. The round tests whether that first version makes the later ones (nested sources, data that changes, several consumers) small changes.

Hello Interview names “resumable iterators” among OpenAI’s practical problems, each with “several behaviors to implement” (Hello Interviewsecondary · 2026). The reported prompt stops there; the stages below are a plausible progression for practice.

Clarify first

  • Resume where? In the same process, or after a restart? Assume after a restart. Then state must be plain data (JSON), not a Python generator, which can’t be pickled (Python’s built-in way of saving objects).
  • What is underneath? A list, a list of lists (think: files of records), or a paginated API? Assume a list of lists.
  • Can the source change between pause and resume? Assume no at first; it is the likely follow-up.
  • Exactly once? If the consumer crashes after next() but before it finishes processing the item, should that item come back? Assume the caller saves state after processing.

Say it like this: “I’ll assume we resume after a restart, so the state has to be JSON. I’ll start with a list of lists and fixed data, and I expect you’ll change both.”

Answer

Words you need first

  • State: the minimum data needed to continue. Here, two integers: outer (which inner list) and inner (the position inside it).
  • Serializable: can be turned into bytes or text (for example with json.dumps) and turned back without loss.
  • At-least-once: every item is delivered, but some may be delivered twice after a crash. Exactly-once means no duplicates, which needs the processing itself to be safe to repeat (idempotent).

The code

Write a class, not a generator, and keep the position as a tuple you can hand back.

class ResumableIterator:
    """Iterates over a list of lists (think: files of records). State is plain data."""

    def __init__(self, sources, state=None):
        self.sources = sources
        self.outer, self.inner = state if state else (0, 0)

    def __iter__(self):
        return self

    def __next__(self):
        while self.outer < len(self.sources):
            src = self.sources[self.outer]
            if self.inner < len(src):
                item = src[self.inner]
                self.inner += 1
                return item
            self.outer, self.inner = self.outer + 1, 0      # skips empty sources too
        raise StopIteration

    def get_state(self):
        return (self.outer, self.inner)                     # JSON-safe: survives a restart

The while loop does two jobs at once. It moves to the next source when the current one is used up, and it skips empty sources without a special case.

One run through it

Take the sources [["a", "b"], [], ["c", "d", "e"]]: three files, the middle one empty. These values come from running the class above.

StepWhat happensState afterWhat to say in the interview
1next() returns "a", then "b"(0, 2)“The state points just past the last item returned.”
2next() finds file 0 used up, skips empty file 1, returns "c"(2, 1)“Empty sources need no special case; the loop skips them.”
3json.dumps(get_state()) gives [2, 1]; the process stopssaved”Two integers is the whole checkpoint.”
4A new iterator is built from [2, 1] and drained(3, 0)“It returns d, e, then stops. a b c plus d e is the full sequence.”

The test that matters does exactly this: read three items, serialize the state with json.dumps, build a new iterator from it, and check that the two halves join into the full sequence. Include empty inner lists and a state at the very end. That test passed when run on 2026-10-12.

How the likely follow-ups change it

  • Composed iterators (a filter over a flatten over files): each layer’s state is its own position plus the state of the layer beneath, so get_state() returns a nested tuple. Keep each layer’s state separate; don’t squash it into one index.
  • Sources that change: an index into a list breaks if items are inserted before it, because the same number now points at a different item. Resume by a stable key instead (the last id or timestamp seen), the way a pagination cursor works in an API.
  • Thread safety: two consumers calling next() at once race on inner and can get the same item. Lock around read-and-advance, or give each consumer its own iterator over a separate slice of the data.
  • Exactly once: state saved after processing gives at-least-once. Say so, and make processing idempotent.

Say it like this when the data starts changing: “A position is only stable if the data is. I’ll switch to resuming from the last key I processed, like an API cursor.”

Senior vs Staff

Resumable iterator

Senior

  • Explicit, serializable state; handles empty sources and the end state; tests resume across a JSON round trip.

Staff

  • Raises cursor-versus-offset when sources change, composes state across layers, and names the delivery guarantee (at-least-once unless processing is idempotent).

Small-team version

You will write this for real. A common AI job is a backfill: a script that runs once over every row of a table, for example calling a model on each document to compute its embedding (a list of numbers that represents the document’s meaning, used for search). Such a job takes hours, costs money per call, and gets interrupted.

It must resume without redoing hours of paid work:

  • Store a stable cursor (the last primary key processed) in your database after each batch, not an in-memory offset.
  • Make each item’s processing idempotent, for example by writing results with an upsert keyed by the document id. Then the at-least-once replay of the last batch costs a few duplicate model calls, not duplicate rows.
  • Buy before you build: a job framework with checkpoints can do this for you. Check that its checkpoint is written after your side effect, not before; otherwise a crash skips items silently.

Pitfalls

  • Using a generator. You discover too late that its position can’t be saved.
  • Resuming by list offset over data that changes. An insert shifts every later item, so you skip or repeat.
  • Missing the edge cases. Empty inner lists and a saved state at the very end are where off-by-one bugs live.
  • Claiming exactly-once. Without idempotent processing, a crash between processing and saving repeats work.

Go deeper

Family