Resumable Iterator
You're building part of a batch pipeline. A job reads items, stops, and starts again later, and it must pick up exactly where it stopped without reprocessing or skipping anything. An ordinary iterator can't do that, because its position disappears with it.
Build an iterator whose whole position is one integer you can save and restore. Then make a list of these iterators behave as one, with a single global position across all of them.
What's in the codebase
iterator.py.ResumableIteratorandCombinedIterator. The constructors and input validation are written, and the eight methods you implement raiseNotImplementedError. This is the only file you change.test_iterator.py. Eighteen tests: ten forResumableIteratorand eight forCombinedIterator, covering order, exhaustion, state round trips, resuming from a fresh iterator, invalid states, and empty inputs.scenarios.py. Pauses and resumes a single iterator, then a combined one. PrintsPASSwhen both resume correctly.README.md. Run commands and ground rules.
Out of the box, the two construction tests pass because the constructors already reject non-list input. The other 16 error.
Your task
Implement next, hasNext, getState, and setState on both classes. Keep the camelCase method names, since the tests call them.
For ResumableIterator, the state is the index of the next item to return, from 0 to the list's length. next raises StopIteration when the iterator is exhausted. setState raises ValueError for anything that isn't an integer in range, and a bool counts as invalid even though Python treats True as 1.
For CombinedIterator, next walks the inner iterators in order, skipping exhausted and empty ones. getState returns the global index, the sum of the inner states. setState splits a global index back across the inner iterators, filling each one to its length before moving to the next, and validates against the total item count.
it = ResumableIterator([10, 20, 30, 40]); it.next(); it.next(); it.getState() -> 2 fresh = ResumableIterator([10, 20, 30, 40]); fresh.setState(2); fresh.next() -> 30 ResumableIterator(["a", "b"]).setState(3) -> ValueError ResumableIterator(["a", "b"]).setState(True) -> ValueError c = CombinedIterator([ResumableIterator([1, 2]), ResumableIterator([3]), ResumableIterator([4, 5])]) five calls to c.next() -> 1, 2, 3, 4, 5 c.setState(3); c.next() -> 4 CombinedIterator([]).hasNext() -> False
You're done when all 18 tests pass and python3 scenarios.py prints PASS.
The checkpoint follow-up
The interviewer probes the state design. You save state 2, then the job restarts against a list with a new item inserted at the front. What happens, and how would you detect it? What goes wrong if the caller advances an inner iterator directly while a CombinedIterator also uses it?
Using AI on this problem
Senior coding rounds like this often allow AI for lookups, such as why isinstance(True, int) is true. Decide the state model and the split rule for CombinedIterator.setState yourself, because those are what the interviewer is grading. If AI writes the validation, check that it rejects a bool before checking for int.
Approach
- Keep the list and one index.
nextreads at the index and advances,hasNextcompares the index with the length, andgetStatereturns the index. - In
setState, reject aboolfirst, then anything that isn't anint, then anything out of range. Validate everything before assigning, so a bad state changes nothing. - Build
CombinedIteratorfrom the inner methods.nextasks each inner iterator in turn,hasNextis true if any inner iterator has more, andgetStatesums the inner states. - Make
setStatethe inverse of that sum: give each inner iterator as much of the remaining index as it can hold, in order.
The two setState methods carry most of the signal:
Python# ResumableIterator
def setState(self, state):
if isinstance(state, bool) or not isinstance(state, int):
raise ValueError("state must be an int")
if not 0 <= state <= len(self._items):
raise ValueError("state out of range")
self._index = state
# CombinedIterator
def setState(self, state):
if isinstance(state, bool) or not isinstance(state, int):
raise ValueError("state must be an int")
total = sum(len(it) for it in self._iterators)
if not 0 <= state <= total:
raise ValueError("state out of range")
remaining = state
for it in self._iterators:
share = min(remaining, len(it))
it.setState(share)
remaining -= share
ResumableIterator is O(1) per call. CombinedIterator.next is O(k) in the number of inner iterators, because it scans from the front each time. Tracking the current inner position would make it O(1), but the scan keeps the state in one place: the inner iterators. Because the global state is a sum and setState fills in order, getState after setState(n) always returns n. Empty inner iterators need no special case, since their hasNext is false.
All 18 tests pass and scenarios.py prints PASS.
What to focus on
- Say what the state is before coding. The iterator remembers one integer, not a copy of the list or the items it returned. That choice makes saving and resuming trivial.
- Check for
boolbeforeint.isinstance(True, int)is true, so a plainintcheck acceptsTrueas index 1. - Validate, then assign. A
setStatethat moves the index and then raises leaves the iterator somewhere no caller expects. - Make the split the inverse of the sum. Any other way of distributing the global index breaks the round trip through
getState.
The checkpoint follow-up
An index only means something against the list it came from. If an item is inserted at the front between getState and setState, resuming at 2 reprocesses one item and nothing in the integer reveals it. Production checkpoints store more than the offset: the list's length and a fingerprint, such as a hash of its contents or a version number from the source. On resume, compare the fingerprint first and refuse a stale state instead of resuming into the wrong data.
The shared inner iterator is the same problem as two consumers reading one queue partition. If the caller calls next on an inner iterator directly, the combined global index jumps without the combined iterator returning anything. The fix is ownership: CombinedIterator should be the only reader, either by documentation or by copying the inner lists when it's constructed.