Fixed-Stride Stream Iterator
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build a SteppedIterator class (along with the evaluation driver stepped_iterator) that wraps an arbitrary single-pass iterator or iterable and surfaces every step-th item starting from position 0.
Given an input source and a positive stride step >= 1 (raising ValueError if step < 1), SteppedIterator must satisfy these behavioral rules:
- Initial item: The very first item produced by
next()is the element at 0-based position0of the wrapped source (when non-empty). - Fixed-stride advancement: Every later
next()call discardsstep - 1intermediate items from the source and returns the following item (positionsstep,2 * step,3 * step, and so on). - Exhaustion: Once no further stepped item exists—including when fewer than
stepitems remain after the previous stepped item—next()raisesStopIteration. - Idempotent lookahead (
hasNext()):hasNext()returnsTrueif another stepped item can be produced andFalseotherwise. RepeatedhasNext()calls with no interveningnext()must return the same boolean without advancing further or dropping any item (even when items areNone,0,False, or""). - Streaming guarantee: The wrapped source may be a lazy one-pass generator with no random indexing, no
len(), and potentially unbounded length, soSteppedIteratormust hold onlyO(1)auxiliary state.
In the test harness function stepped_iterator(values, step, operations, arguments), instantiate SteppedIterator(iter(values), step) and execute each command in operations ("hasNext" or "next"), recording None whenever next() raises StopIteration.
from typing import Any, Iterator, List
class SteppedIterator:
def __init__(self, iterator: Iterator[Any], step: int) -> None:
pass
def hasNext(self) -> bool:
pass
def next(self) -> Any:
pass
def stepped_iterator(
values: List[int],
step: int,
operations: List[str],
arguments: List[List],
) -> List[object]:
pass
Examples
Example 1
Input:
values = [4, 8, 12, 16, 20, 24]
step = 2
operations = ["hasNext", "hasNext", "next", "next", "hasNext", "next", "hasNext", "next"]
arguments = [[], [], [], [], [], [], [], []]
Output:
[True, True, 4, 12, True, 20, False, None]
Explanation: Positions 0, 2, 4 hold 4, 12, 20 (while 24 at position 5 sits inside an incomplete trailing stride). Two consecutive hasNext() calls both return True without losing 4. Subsequent next() and hasNext() calls yield 4, 12, True, and 20. After 20, only one element (24) remains instead of two, so hasNext() returns False and a final next() raises StopIteration (recorded as None).
Example 2
Input:
values = [11, 22, 33, 44, 55]
step = 3
operations = ["next", "hasNext", "next", "hasNext", "next"]
arguments = [[], [], [], [], []]
Output:
[11, True, 44, False, None]
Explanation: The first next() returns position 0 (11). Calling hasNext() skips two elements (22, 33), buffers position 3 (44), and returns True; the following next() returns 44. Trying to advance by 3 again runs out after 55, so hasNext() returns False and next() records None.
Constraints
1 <= step <= 10^90 <= len(values) <= 10^6in the harness (SteppedIteratoritself may also wrap unbounded generators).- Worst-case work per
hasNext()ornext()call must beO(step)pulls from the underlying iterator (stopping early as soon as the iterator ends). - Auxiliary memory must be
O(1).
Step-by-step walkthrough
Understand the problem and constraints
We want a
SteppedIteratorclass that wraps any input iterator (or iterable) and produces the items at positions0, k, 2k, 3k, ...wherek = step >= 1:Underlying stream: [ 4, 8, 12, 16, 20, 24 ] Indices: 0 1 2 3 4 5 step = 2 yields: 4 (skip) 12 (skip) 20 (skip -> end)Every method call must obey four rules:
next()returns position0on the initial call, then skipsstep - 1items to return positionsstep, 2 * step, ..., raisingStopIterationwhen no stepped item remains.hasNext()returnsTruewhen another stepped item is available andFalseotherwise. RepeatedhasNext()calls with nonext()in between must be idempotent (every call returns the same answer without moving forward).- The wrapped source may be a one-pass iterator (such as a generator or file reader) with no
len(), no random indexing, no rewind capability, and potentially infinite length. - Auxiliary memory must remain
O(1).
In the judge wrapper
stepped_iterator(values, step, operations, arguments), each"hasNext"or"next"output is appended to a result list, withStopIterationmapped toNone.Why converting to a list or advancing blindly fails
Two tempting shortcuts break right away:
- Materializing a list (
list(iterator)[::step]): Pulls the entire stream into RAM up front. That usesO(n)space instead ofO(1), wastes work if the caller reads only two items, and hangs forever on an unbounded generator. - Pulling inside
hasNext()without saving the item: Because a one-pass iterator cannot "peek" or push an item back, the only wayhasNext()can check whether item2kexists is to actually callnext()on the wrapped iterator. If we fail to stash that pulled item somewhere, the followingit.next()call will miss it!
- Materializing a list (
Key idea: a lazy one-element lookahead buffer
We solve the peek problem by keeping a single holding slot (a one-element lookahead buffer) inside
SteppedIteratorand filling it lazily (only when a caller invokeshasNext()ornext()while the slot is empty):discard (step - 1) items pull 1 item into slot Underlying _it ──────────────────────────► [ _buffer | _has_buffer=True ] ──► returned by next() (0 items discarded at index 0)Four small state fields keep every transition unambiguous:
_started(bool):Falsebefore we attempt index0,Trueafterward. Index0skips zero items; every later load skipsstep - 1items before capturing the next one._has_buffer(bool) and_buffer(Any): whether the slot currently holds a valid item, and that item itself. We use a separate boolean flag rather than checking_buffer is not NonebecauseNone,0, andFalseare completely valid items in Python iterators!_exhausted(bool): becomesTruethe first time the wrapped iterator raisesStopIteration, so we never touch a finished iterator again.
Implement the lazy loader `_load()`
Both
hasNext()andnext()start by calling_load(). Notice two critical details:- If
_has_bufferis alreadyTrue(for instance,hasNext()was just called),_load()returns immediately—making repeatedhasNext()calls free and idempotent. - A single
try ... except StopIterationblock wraps both theskip_countloop and the finalnext(self._it)pull. Ifstep = 10^9on a 3-element input, the second_load()tries to skip, hitsStopIterationafter 2 pulls, marks_exhausted = True, and finishes immediately instead of looping10^9times!
class SteppedIterator: """Wrap any one-pass iterator and yield elements at indices 0, step, 2*step, ...""" def __init__(self, iterator, step: int): if step < 1: raise ValueError("step must be a positive integer") # iter(...) accepts both an existing iterator and any iterable sequence. self._it = iter(iterator) self._step = step # State for our lazy 1-element lookahead slot: # - _started: False before index 0 is attempted, True afterward # - _has_buffer: separate bool because None/0/False are valid data values # - _buffer: holds the next stepped element once pulled # - _exhausted: True once self._it raises StopIteration so we never touch it again self._started = False self._has_buffer = False self._buffer: Any = None self._exhausted = False def _load(self) -> None: """Lazily fill `_buffer` with the next stepped element if it is currently empty.""" # Fast exit keeps repeated hasNext() calls idempotent and avoids touching dead iterators. if self._has_buffer or self._exhausted: return # Index 0 requires 0 skips; moving from k to k + step skips (step - 1) items in between. if self._started: skip_count = self._step - 1 else: skip_count = 0 self._started = True # Catch StopIteration across BOTH skipping and pulling so a short tail stops immediately. try: for _ in range(skip_count): next(self._it) self._buffer = next(self._it) self._has_buffer = True except StopIteration: self._exhausted = True- If
Implement `hasNext`, `next`, and the judge driver
Once
_load()guarantees the buffer is populated whenever another stepped element exists,hasNext()andnext()become tiny:hasNext()calls_load()and returns_has_buffer.next()calls_load(), raisesStopIterationif_has_bufferisFalse, and otherwise grabs_buffer, resets_has_buffer = Falseand_buffer = None, and returns the value. Clearing_has_bufferis what tells the next call to advance bystep.
def hasNext(self) -> bool: """Return True if at least one more stepped element exists, without losing it.""" self._load() return self._has_buffer def next(self) -> Any: """Consume and return the next stepped element, or raise StopIteration.""" self._load() if not self._has_buffer: raise StopIteration # Consume the buffered slot so the next call will advance by `step` again. value = self._buffer self._buffer = None self._has_buffer = False return value def stepped_iterator( values: List[int], step: int, operations: List[str], arguments: List[List], ) -> List[object]: it = SteppedIterator(iter(values), step) results: List[object] = [] for op in operations: if op == "hasNext": results.append(it.hasNext()) elif op == "next": try: results.append(it.next()) except StopIteration: # The judge harness represents a next() call past exhaustion as None. results.append(None) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 2 step by step
Let's trace
values = [11, 22, 33, 44, 55],step = 3, andoperations = ['next', 'hasNext', 'next', 'hasNext', 'next']:Call Action inside _load() Slot after call Exhausted? Output ──────── ─────────────────────────────────────────── ────────────────── ────────── ────── (init) nothing pulled yet empty False — next() first load: skip 0, pull 11 -> consumed empty False 11 hasNext() skip 2 items (22, 33), pull 44 into slot 44 False True next() slot already full -> consume 44 empty False 44 hasNext() skip 2 items: pulls 55, next pull raises! empty True False next() _exhausted is True -> raises StopIteration empty True NoneThe returned list is
[11, True, 44, False, None], matching Example 2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class SteppedIterator: """Wrap any one-pass iterator and yield elements at indices 0, step, 2*step, ...""" def __init__(self, iterator, step: int): if step < 1: raise ValueError("step must be a positive integer") # iter(...) accepts both an existing iterator and any iterable sequence. self._it = iter(iterator) self._step = step # State for our lazy 1-element lookahead slot: # - _started: False before index 0 is attempted, True afterward # - _has_buffer: separate bool because None/0/False are valid data values # - _buffer: holds the next stepped element once pulled # - _exhausted: True once self._it raises StopIteration so we never touch it again self._started = False self._has_buffer = False self._buffer: Any = None self._exhausted = False def _load(self) -> None: """Lazily fill `_buffer` with the next stepped element if it is currently empty.""" # Fast exit keeps repeated hasNext() calls idempotent and avoids touching dead iterators. if self._has_buffer or self._exhausted: return # Index 0 requires 0 skips; moving from k to k + step skips (step - 1) items in between. if self._started: skip_count = self._step - 1 else: skip_count = 0 self._started = True # Catch StopIteration across BOTH skipping and pulling so a short tail stops immediately. try: for _ in range(skip_count): next(self._it) self._buffer = next(self._it) self._has_buffer = True except StopIteration: self._exhausted = True def hasNext(self) -> bool: """Return True if at least one more stepped element exists, without losing it.""" self._load() return self._has_buffer def next(self) -> Any: """Consume and return the next stepped element, or raise StopIteration.""" self._load() if not self._has_buffer: raise StopIteration # Consume the buffered slot so the next call will advance by `step` again. value = self._buffer self._buffer = None self._has_buffer = False return value def stepped_iterator( values: List[int], step: int, operations: List[str], arguments: List[List], ) -> List[object]: it = SteppedIterator(iter(values), step) results: List[object] = [] for op in operations: if op == "hasNext": results.append(it.hasNext()) elif op == "next": try: results.append(it.next()) except StopIteration: # The judge harness represents a next() call past exhaustion as None. results.append(None) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture items arriving along a one-way conveyor belt—a one-pass iterator (a stream you can read forward once, without seeing its length or putting items back). A caller can ask "Do you have another item?" (hasNext()) several times in a row before saying "Give it to me" (next()), meaning hasNext() must be idempotent (calling it repeatedly returns the exact same answer without altering the state). Because the only way to discover whether the next stepped item exists is to run the belt forward and try to grab it, we place a tiny one-item holding tray—a lookahead buffer (a single slot that stores one already-pulled item until next() consumes it)—right beside the belt.
Why do simpler approaches fail? Converting the input with list(iterator)[::step] pulls the entire stream into RAM up front, violating O(1) memory and hanging forever on an infinite generator. On the other hand, advancing the wrapped iterator inside hasNext() without saving the pulled item loses that item permanently, and loading the next item eagerly inside __init__ or at the end of next() consumes items the caller never asked for. Instead, we use lazy evaluation (doing the skip-and-pull work inside _load() only when hasNext() or next() needs an item and the tray is empty).
Let's trace Example 2 on source = iter([11, 22, 33, 44, 55]) with step = 3:
1. next() -> tray empty, first load (skip 0): pull 11 onto tray, then hand back 11 (tray empty)
2. hasNext() -> tray empty, later load (skip 3-1 = 2): discard 22 and 33, pull 44 onto tray -> True
3. next() -> tray already holds 44 -> hand back 44 and clear tray
4. hasNext() -> tray empty, later load (skip 2): discard 55, next pull hits StopIteration!
mark exhausted = True, tray stays empty -> return False
5. next() -> exhausted is True -> raise StopIteration (recorded as None by harness)
Complexity
Let step be the stride and n be the total number of elements in a finite wrapped iterator.
- Time:
O(step)worst-case perhasNext()ornext()call (O(1)when already buffered), andO(n)across a full traversal. When the lookahead buffer is empty,_load()discards at moststep - 1items and pulls1target item—at moststepcalls tonext(self._it). When the buffer is already full (such as anext()right afterhasNext(), or repeatedhasNext()calls),_load()returns inO(1)time. Across an entire pass overnitems, each source item is pulled at most once. - Space:
O(1)auxiliary memory.SteppedIteratorstores only the iterator reference,_step,_buffer, and three boolean flags (_started,_has_buffer,_exhausted), independent ofnandstep.
Edge cases
step == 1:skip_countis0on the first load and1 - 1 = 0on every later load, so every item is yielded in order just like the source iterator.- Empty source iterator: The very first
_load()catchesStopIterationimmediately;hasNext()returnsFalseandnext()raisesStopIteration. - Fewer items remaining than
step(includingstep = 10^9on 3 items): As soon asnext(self._it)runs out of items inside the skip loop,StopIterationexits the loop right away—doing at mostremaining + 1pulls rather than10^9iterations. - Consecutive
hasNext()calls: Only the first call pulls fromself._it; subsequent calls hitif self._has_buffer: returnand returnTruewithout advancing. - Calling
next()without callinghasNext()first: Works seamlessly becausenext()also callsself._load()before checking the buffer. None,0,False, or""in the input stream: Because_has_buffertracks occupancy separately from_buffer(an alternative is a unique private sentinel object,_EMPTY = object(), that can never equal any caller value), falsy values andNoneare never confused with an empty buffer.- Clearing
_buffer = Noneonnext(): Releases the reference to the consumed object immediately so large objects can be garbage-collected right away.
Common mistakes
- Skipping
step - 1items before index0: That returns indexstep - 1first instead of index0. The first load must skip0items, and only subsequent loads skipstep - 1. - Advancing by
stepinstead ofstep - 1between items: Pulling the target item itself already advances the iterator by1position, so skippingstepitems before pulling lands on0, step + 1, 2 * step + 2, ...(an off-by-one bug!). - Using
_buffer is Noneto mean "buffer is empty": Silently dropsNoneelements from iterators likeiter([None, 1, None]). - Catching
StopIterationonly around the final pull and not the skip loop: If the stream ends mid-skip,StopIterationleaks uncaught out ofhasNext()instead of returningFalse. - Calling
list(iterator)orlen(iterator): Crashes on generators (TypeError: object of type 'generator' has no len()), violatesO(1)memory, and hangs on infinite streams.
Alternative approaches
- Wrapping
itertools.islice(iterator, 0, None, step): Python's standardisliceyields indices0, step, 2 * step, ...lazily in C. Because Python iterators still lackhasNext(), you still need the exact same 1-element lookahead buffer around theisliceobject, though_startedand the manual skip loop disappear. - Sentinel object instead of
_has_buffer: Defining_EMPTY = object()at module level lets a single attributeself._buffer = _EMPTYrepresent both states (self._buffer is not _EMPTY), saving one boolean flag with identical behavior.
Follow-up questions
- How would you design a
setStep(new_step)mutator that updates the stride mid-iteration, especially if an element is already buffered? Validatenew_step >= 1and assignself._step = new_step. Whenever_has_bufferisFalse(for example, immediately afternext()or before any call), the next_load()naturally skipsnew_step - 1items with no extra state! If a caller already invokedhasNext()—filling_bufferunder the previous stride—before callingsetStep(new_step), a one-pass iterator cannot rewind whennew_step < old_step, and discarding the buffered value whennew_step > old_stepcould contradict theTruejust returned byhasNext(). DefiningsetStepto take effect starting after any currently buffered item is consumed keepshasNext()faithful while supporting dynamic strides cleanly. - When the wrapped input is an indexable sequence such as a
listortuple, how can you drop the per-call work fromO(step)toO(1)? Checkisinstance(iterator, collections.abc.Sequence)inside__init__before callingiter(...). WhenTrue, keep a reference to the sequence and an integer cursorself._cursor = 0:hasNext()becomesself._cursor < len(self._seq)inO(1)time, andnext()readsself._seq[self._cursor]and incrementsself._cursor += self._stepinO(1)time andO(1)auxiliary space (avoidingseq[::step], which allocates anO(n / step)slice copy). - What synchronization changes are needed if multiple threads share a single
SteppedIteratorinstance? GuardhasNext()andnext()with athreading.Lockso concurrent callers never corrupt_buffer/_startedor enter the same Python generator simultaneously (which raisesValueError: generator already executing). Keep_load()as an internal helper invoked only while the lock is held, or use a reentrant lock (threading.RLock, a lock the owning thread can re-acquire safely). Because separateif it.hasNext(): val = it.next()calls still allow another thread to steal the final item in between, concurrent APIs should also offer a single atomictry_next() -> Tuple[bool, Any]method that checks and consumes under one lock acquisition.
Follow-up questions
- How would you design a `setStep(new_step)` mutator that updates the stride mid-iteration, especially if an element is already buffered?
- When the wrapped input is an indexable sequence such as a `list` or `tuple`, how can you drop the per-call work from `O(step)` to `O(1)`?
- What synchronization changes are needed if multiple threads share a single `SteppedIterator` instance?
Similar questions
- Find Extreme Dictionary by Dynamic Key
- Sparse Minesweeper Engine and Flood-Fill Optimization
- Email and Password Authentication Service
- Canonical Unix Path and Lazy Nested-List Iterator
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target