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:

  1. Initial item: The very first item produced by next() is the element at 0-based position 0 of the wrapped source (when non-empty).
  2. Fixed-stride advancement: Every later next() call discards step - 1 intermediate items from the source and returns the following item (positions step, 2 * step, 3 * step, and so on).
  3. Exhaustion: Once no further stepped item exists—including when fewer than step items remain after the previous stepped item—next() raises StopIteration.
  4. Idempotent lookahead (hasNext()): hasNext() returns True if another stepped item can be produced and False otherwise. Repeated hasNext() calls with no intervening next() must return the same boolean without advancing further or dropping any item (even when items are None, 0, False, or "").
  5. Streaming guarantee: The wrapped source may be a lazy one-pass generator with no random indexing, no len(), and potentially unbounded length, so SteppedIterator must hold only O(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^9
  • 0 <= len(values) <= 10^6 in the harness (SteppedIterator itself may also wrap unbounded generators).
  • Worst-case work per hasNext() or next() call must be O(step) pulls from the underlying iterator (stopping early as soon as the iterator ends).
  • Auxiliary memory must be O(1).

Step-by-step walkthrough

  1. Understand the problem and constraints

    We want a SteppedIterator class that wraps any input iterator (or iterable) and produces the items at positions 0, k, 2k, 3k, ... where k = 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 position 0 on the initial call, then skips step - 1 items to return positions step, 2 * step, ..., raising StopIteration when no stepped item remains.
    • hasNext() returns True when another stepped item is available and False otherwise. Repeated hasNext() calls with no next() 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, with StopIteration mapped to None.

  2. Why converting to a list or advancing blindly fails

    Two tempting shortcuts break right away:

    1. Materializing a list (list(iterator)[::step]): Pulls the entire stream into RAM up front. That uses O(n) space instead of O(1), wastes work if the caller reads only two items, and hangs forever on an unbounded generator.
    2. Pulling inside hasNext() without saving the item: Because a one-pass iterator cannot "peek" or push an item back, the only way hasNext() can check whether item 2k exists is to actually call next() on the wrapped iterator. If we fail to stash that pulled item somewhere, the following it.next() call will miss it!
  3. 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 SteppedIterator and filling it lazily (only when a caller invokes hasNext() or next() 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): False before we attempt index 0, True afterward. Index 0 skips zero items; every later load skips step - 1 items 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 None because None, 0, and False are completely valid items in Python iterators!
    • _exhausted (bool): becomes True the first time the wrapped iterator raises StopIteration, so we never touch a finished iterator again.
  4. Implement the lazy loader `_load()`

    Both hasNext() and next() start by calling _load(). Notice two critical details:

    • If _has_buffer is already True (for instance, hasNext() was just called), _load() returns immediately—making repeated hasNext() calls free and idempotent.
    • A single try ... except StopIteration block wraps both the skip_count loop and the final next(self._it) pull. If step = 10^9 on a 3-element input, the second _load() tries to skip, hits StopIteration after 2 pulls, marks _exhausted = True, and finishes immediately instead of looping 10^9 times!
    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
    
  5. Implement `hasNext`, `next`, and the judge driver

    Once _load() guarantees the buffer is populated whenever another stepped element exists, hasNext() and next() become tiny:

    • hasNext() calls _load() and returns _has_buffer.
    • next() calls _load(), raises StopIteration if _has_buffer is False, and otherwise grabs _buffer, resets _has_buffer = False and _buffer = None, and returns the value. Clearing _has_buffer is what tells the next call to advance by step.
    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
    
  6. Trace Example 2 step by step

    Let's trace values = [11, 22, 33, 44, 55], step = 3, and operations = ['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        None
    

    The returned list is [11, True, 44, False, None], matching Example 2.

  7. 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 per hasNext() or next() call (O(1) when already buffered), and O(n) across a full traversal. When the lookahead buffer is empty, _load() discards at most step - 1 items and pulls 1 target item—at most step calls to next(self._it). When the buffer is already full (such as a next() right after hasNext(), or repeated hasNext() calls), _load() returns in O(1) time. Across an entire pass over n items, each source item is pulled at most once.
  • Space: O(1) auxiliary memory. SteppedIterator stores only the iterator reference, _step, _buffer, and three boolean flags (_started, _has_buffer, _exhausted), independent of n and step.

Edge cases

  • step == 1: skip_count is 0 on the first load and 1 - 1 = 0 on every later load, so every item is yielded in order just like the source iterator.
  • Empty source iterator: The very first _load() catches StopIteration immediately; hasNext() returns False and next() raises StopIteration.
  • Fewer items remaining than step (including step = 10^9 on 3 items): As soon as next(self._it) runs out of items inside the skip loop, StopIteration exits the loop right away—doing at most remaining + 1 pulls rather than 10^9 iterations.
  • Consecutive hasNext() calls: Only the first call pulls from self._it; subsequent calls hit if self._has_buffer: return and return True without advancing.
  • Calling next() without calling hasNext() first: Works seamlessly because next() also calls self._load() before checking the buffer.
  • None, 0, False, or "" in the input stream: Because _has_buffer tracks occupancy separately from _buffer (an alternative is a unique private sentinel object, _EMPTY = object(), that can never equal any caller value), falsy values and None are never confused with an empty buffer.
  • Clearing _buffer = None on next(): Releases the reference to the consumed object immediately so large objects can be garbage-collected right away.

Common mistakes

  • Skipping step - 1 items before index 0: That returns index step - 1 first instead of index 0. The first load must skip 0 items, and only subsequent loads skip step - 1.
  • Advancing by step instead of step - 1 between items: Pulling the target item itself already advances the iterator by 1 position, so skipping step items before pulling lands on 0, step + 1, 2 * step + 2, ... (an off-by-one bug!).
  • Using _buffer is None to mean "buffer is empty": Silently drops None elements from iterators like iter([None, 1, None]).
  • Catching StopIteration only around the final pull and not the skip loop: If the stream ends mid-skip, StopIteration leaks uncaught out of hasNext() instead of returning False.
  • Calling list(iterator) or len(iterator): Crashes on generators (TypeError: object of type 'generator' has no len()), violates O(1) memory, and hangs on infinite streams.

Alternative approaches

  • Wrapping itertools.islice(iterator, 0, None, step): Python's standard islice yields indices 0, step, 2 * step, ... lazily in C. Because Python iterators still lack hasNext(), you still need the exact same 1-element lookahead buffer around the islice object, though _started and the manual skip loop disappear.
  • Sentinel object instead of _has_buffer: Defining _EMPTY = object() at module level lets a single attribute self._buffer = _EMPTY represent 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? Validate new_step >= 1 and assign self._step = new_step. Whenever _has_buffer is False (for example, immediately after next() or before any call), the next _load() naturally skips new_step - 1 items with no extra state! If a caller already invoked hasNext()—filling _buffer under the previous stride—before calling setStep(new_step), a one-pass iterator cannot rewind when new_step < old_step, and discarding the buffered value when new_step > old_step could contradict the True just returned by hasNext(). Defining setStep to take effect starting after any currently buffered item is consumed keeps hasNext() faithful while supporting dynamic strides cleanly.
  • 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)? Check isinstance(iterator, collections.abc.Sequence) inside __init__ before calling iter(...). When True, keep a reference to the sequence and an integer cursor self._cursor = 0: hasNext() becomes self._cursor < len(self._seq) in O(1) time, and next() reads self._seq[self._cursor] and increments self._cursor += self._step in O(1) time and O(1) auxiliary space (avoiding seq[::step], which allocates an O(n / step) slice copy).
  • What synchronization changes are needed if multiple threads share a single SteppedIterator instance? Guard hasNext() and next() with a threading.Lock so concurrent callers never corrupt _buffer / _started or enter the same Python generator simultaneously (which raises ValueError: 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 separate if it.hasNext(): val = it.next() calls still allow another thread to steal the final item in between, concurrent APIs should also offer a single atomic try_next() -> Tuple[bool, Any] method that checks and consumes under one lock acquisition.

Follow-up questions

Similar questions

More Bridge interview questions

All 5 Bridge questions →