Resumable Iterator
On this page
Problem statement
Build an iterator that can save and restore its position. It supports
has_next(),next(),get_state()andset_state(state).get_state()returns a plain value (something you could write as JSON); passing it toset_statelater, even on a fresh iterator over the same data in a new process, makes the iterator continue exactly from where the state was taken. Part 1: over a list. Part 2: over several sources in sequence (lists or files, some of them empty), where each source is itself resumable. Part 3: over the lines of a real file, without reading the whole file.
This is the kind of class a data-loading pipeline needs: a long training or ETL job crashes, and you want to restart from the last checkpoint instead of from the start. It is usually run in stages, and the interviewer watches how your state design holds up as sources get nested. There is no LeetCode original; LeetCode 341 Flatten Nested List Iterator and LeetCode 251 Flatten 2D Vector are the closest warm-ups.
Example

it = ListIterator([10, 20, 30, 40, 50])
it.next() -> 10
it.next() -> 20
s = it.get_state() # {"i": 2}
it.next() -> 30
it.next() -> 40
it.set_state(s)
it.next() -> 30
ch = ChainIterator([ListIterator([1, 2]), ListIterator([]), ListIterator([3, 4, 5])])
ch.next(), ch.next(), ch.next() -> 1, 2, 3
s = ch.get_state() # {"k": 2, "inner": {"i": 1}}
ch.next(), ch.next() -> 4, 5
ch.set_state(s)
ch.next() -> 4
Constraints (assumed)
- Sources can be large (files of many GB), so the state must be O(1) or O(depth), never a copy of the data.
- The data does not change between saving and restoring a state.
- Single-threaded; concurrency is a follow-up.
What this question tests
- Designing a state that is small, complete and independent of the live iterator (a value, not a reference).
- Composition: an iterator built from other iterators, whose state contains their states.
- Careful handling of boundaries: empty sources, the end of a source, restoring after exhaustion.
Questions to ask first
- Does the state have to survive a restart (serialisable), or only live in memory? (Here: serialisable, so JSON-friendly values.)
- Can the underlying data change between save and restore? (Here: no. If it can, you need versioning or record IDs.)
- Can a state be restored more than once, or on a different iterator instance? (Here: yes to both.)
- What should
next()do at the end? (Here: raise;has_next()returns false.) - For files: can I use byte offsets? They are the natural cheap position.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.