Design a Lazy Iterator Pipeline with Range and Combinators
Data Structure DesignModel answerLast updated
Build a pull-based iterator for ranges with configurable steps and endpoints, plus composable transformations like map, filter, zip, take, drop, and chain.
Design and implement an iterator library in your preferred language that supports the following:
Core range iterator:
- Create ranges with
range(start, end, step)wherestepcan be positive or negative - Support both exclusive and inclusive endpoint modes
- Handle edge cases: empty ranges, backward iteration, extremely large bounds
- Ensure the implementation never overflows when computing intermediate values
Lazy combinators: Each combinator should operate lazily (no upfront materialization) and use constant extra space:
map(f)— apply a function to each elementfilter(pred)— keep only elements satisfying a predicatezip(*others)— combine multiple iterators element-wisetake(n)— yield at most n elementsdrop(n)— skip the first n elementschain(*others)— concatenate multiple iterators sequentially
Peekable wrapper:
peek()— return the next element without consuming ithasNext()— check if more elements are available- Discuss whether
reset()orrewind()can be supported, and under what conditions
Additional considerations:
- Define what happens when an underlying collection is modified while an iterator is active
- Write focused unit tests for boundary scenarios: zero step, single-element ranges, negative steps, very large bounds, empty inputs
- Show example usage demonstrating chained operations
Your solution should be production-ready: handle all edge cases, document complexity, and explain design trade-offs.
Hints
Hint 1
Compute the total element count once at construction rather than checking termination conditions on every step—this avoids overflow and simplifies endpoint logic
Hint 2
Each combinator holds only references and small counters; the actual elements flow through on demand, never stored in bulk
Hint 3
A peekable iterator needs a one-element buffer and a sentinel value to distinguish 'no peek yet' from 'peeked None'
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to build every component as a pull-based iterator where each operator holds minimal state and computes values on demand. This enables efficient chaining without intermediate storage.
Range Design
The naive approach—incrementing a cursor and checking cursor >= end—breaks down in two ways:
- Overflow risk: when
endis near the maximum integer value, computingend + 1or checking termination can overflow - Complexity with negative steps and inclusive bounds: getting the termination condition right across all combinations is error-prone
Solution: Precompute the element count n and generate the i-th element as start + i × step.
For exclusive ranges:
span = |end - start|(in the direction of travel)n = max(0, ⌊(span - 1) / |step|⌋ + 1)
For inclusive ranges:
n = max(0, ⌊span / |step|⌋ + 1)whenspan ≥ 0, else0
Since i × |step| ≤ span, the computation start + i × step never exceeds the closed interval [min(start, end), max(start, end)], eliminating overflow concerns.
Edge case: zero step — reject at construction. Allowing it would imply an infinite stream, which requires explicit design.
Combinator Design
Each combinator wraps one or more source iterators and implements __next__ by delegating to those sources:
- map/filter: stateless wrappers that transform or skip elements
- take: maintains a counter, stops after k elements
- drop: skips n elements on first pull, then forwards everything
- zip: pulls one element from each source, stops when any source is exhausted
- chain: iterates the first source to exhaustion, then moves to the next
All combinators propagate StopIteration naturally.
Peekable Iterator
A peekable wrapper needs a one-slot buffer:
peek()fills the buffer by callingnext()on the sourcenext()drains the buffer first if filled, otherwise pulls from the source- Use a sentinel object (not
None) to distinguish "buffer empty" from "buffered None"
Reset / Rewind
General iterators (file streams, network sockets, arbitrary generators) cannot be rewound without buffering the entire sequence. Compositional reset works when every layer supports it:
- Ranges track an index
i;reset()setsi = 0 - Stateless combinators (
map,filter) forwardreset()to their source - Stateful combinators (
take,drop,chain,peekable) also restore their internal counters and buffers
If any layer wraps a non-rewindable source, reset() raises NotImplementedError. This keeps memory usage O(1) while supporting reset for pure pipelines.
Invalidation Rules
For iterators over mutable collections, use fail-fast semantics:
- The collection maintains a version counter incremented on structural modifications
- The iterator snapshots the version at creation
- Each
next()checks the version and raises if it changed
Ranges are immutable, so they are never invalidated.
Complexity
- Space: O(1) per combinator (just references and counters)
- Time: O(1) per element, except:
filteris O(1) amortized per yielded element (may scan multiple inputs)drop(n)pays O(n) once during the first pull
Implementation (Python)
from typing import Callable, Iterable
_SENTINEL = object()
class Iter:
"""Base class for composable iterators."""
def __iter__(self):
return self
def __next__(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError("Iterator does not support reset")
def map(self, f):
return Map(self, f)
def filter(self, predicate):
return Filter(self, predicate)
def zip(self, *others):
return Zip(self, *others)
def take(self, n):
return Take(self, n)
def drop(self, n):
return Drop(self, n)
def chain(self, *others):
return Chain(self, *others)
def peekable(self):
return Peekable(self)
class Range(Iter):
"""Overflow-safe range iterator with configurable step and endpoint mode."""
def __init__(self, start: int, end: int, step: int = 1, inclusive: bool = False):
if step == 0:
raise ValueError("Step cannot be zero")
self.start = start
self.step = step
# Compute element count in direction of travel
if step > 0:
span = end - start
else:
span = start - end
abs_step = abs(step)
if inclusive:
self.count = max(0, span // abs_step + 1) if span >= 0 else 0
else:
self.count = max(0, (span - 1) // abs_step + 1) if span > 0 else 0
self.index = 0
def __next__(self):
if self.index >= self.count:
raise StopIteration
value = self.start + self.index * self.step
self.index += 1
return value
def reset(self):
self.index = 0
class Map(Iter):
def __init__(self, source, func):
self.source = source
self.func = func
def __next__(self):
return self.func(next(self.source))
def reset(self):
self.source.reset()
class Filter(Iter):
def __init__(self, source, predicate):
self.source = source
self.predicate = predicate
def __next__(self):
while True:
value = next(self.source)
if self.predicate(value):
return value
def reset(self):
self.source.reset()
class Zip(Iter):
def __init__(self, *sources):
self.sources = sources
def __next__(self):
return tuple(next(src) for src in self.sources)
def reset(self):
for src in self.sources:
src.reset()
class Take(Iter):
def __init__(self, source, n):
self.source = source
self.limit = n
self.remaining = n
def __next__(self):
if self.remaining <= 0:
raise StopIteration
self.remaining -= 1
return next(self.source)
def reset(self):
self.source.reset()
self.remaining = self.limit
class Drop(Iter):
def __init__(self, source, n):
self.source = source
self.skip_count = n
self.to_skip = n
def __next__(self):
while self.to_skip > 0:
next(self.source)
self.to_skip -= 1
return next(self.source)
def reset(self):
self.source.reset()
self.to_skip = self.skip_count
class Chain(Iter):
def __init__(self, *sources):
self.sources = list(sources)
self.current_index = 0
def __next__(self):
while self.current_index < len(self.sources):
try:
return next(self.sources[self.current_index])
except StopIteration:
self.current_index += 1
raise StopIteration
def reset(self):
for src in self.sources:
src.reset()
self.current_index = 0
class Peekable(Iter):
def __init__(self, source):
self.source = source
self.buffer = _SENTINEL
def peek(self):
if self.buffer is _SENTINEL:
self.buffer = next(self.source)
return self.buffer
def has_next(self):
try:
self.peek()
return True
except StopIteration:
return False
def __next__(self):
if self.buffer is not _SENTINEL:
value = self.buffer
self.buffer = _SENTINEL
return value
return next(self.source)
def reset(self):
self.source.reset()
self.buffer = _SENTINEL
# Example usage
pipeline = (Range(0, 1000000000, 2)
.filter(lambda x: x % 3 == 0)
.map(lambda x: x * x)
.take(5))
print(list(pipeline)) # [0, 36, 144, 324, 576]
Key Edge Cases
- Empty ranges:
Range(5, 5)orRange(10, 0, 1)return zero elements - Single element inclusive:
Range(5, 5, 1, inclusive=True)yields one element - Negative steps:
Range(10, 0, -2)counts backward - Large bounds: using the formula avoids overflow since intermediate values stay in
[start, end] - take(0) / drop(∞): correctly yield nothing or exhaust the source
- zip with empty: stops immediately
- peek on exhausted iterator: raises StopIteration