Build Iterator Abstractions and Composed Traversals
Data Structure DesignModel answerLast updated
Design an iterator protocol from scratch, implement concrete iterators with different traversal logic, and extend them with features like peeking, filtering, and flattening.
You are working in a minimal environment without standard library iterators. Your task is to build an iterator system from the ground up.
Part 1: Define the core protocol
Create an Iterator interface (or abstract base class) that declares:
hasNext(): returns true if more elements remain, false otherwisenext(): returns the next element and advances the cursor
The contract: hasNext() must be side-effect-free and idempotent. next() must throw an exception if called when no elements remain.
Part 2: Implement two base iterators
- Collection iterator: traverses a backing array or list without copying it
- Generator-style iterator: produces values on demand (e.g., a range from start to stop with a given step)
Part 3: Add three extensions
Implement three additional iterator types that wrap or compose existing iterators:
- Peeking: add a
peek()method that returns the next element without consuming it - Filtering: wrap an iterator and a predicate function; only yield elements that satisfy the predicate
- Flattening: accept an iterator of iterators and yield elements from each inner iterator in sequence
All operations must be lazy: no full-collection materialization, and next() / hasNext() should run in O(1) time except when skipping filtered or empty iterators.
Part 4: Demonstrate correctness
Write test cases covering:
- Empty collections
- Single-element collections
- Exhaustion (calling
next()past the end) - Repeated
hasNext()calls peek()without advancing- Filters that match nothing
- Nested empty iterators in the flattening case
Hints
Hint 1
For peeking, cache one element and track whether the cache is full
Hint 2
Filtering must call the underlying iterator inside hasNext() to find the next match
Hint 3
Flattening requires a loop in the advance logic to skip over multiple empty inner iterators in a row
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is stateful lazy evaluation: each iterator must track its position and, when wrapping another iterator, must not pull all elements upfront.
Contract and invariants
Before writing code, establish the rules:
hasNext()is read-only. Calling it multiple times in a row produces the same result and does not consume elements.next()advances the cursor and returns the current element. If no elements remain, it throws an exception.- Composed iterators (peeking, filtering, flattening) must delegate to their source without copying data.
Base iterators
Collection iterator: maintain an index into the backing collection. Each next() call returns collection[index] and increments index. hasNext() checks whether index < length.
Range iterator: track a current value, the stopping boundary, and the step. Each next() returns the current value and adds the step. hasNext() checks whether the current value has crossed the boundary. Handle both positive and negative steps. Reject step = 0 immediately.
Extension 1: Peeking
Introduce a cache field and a boolean flag. When peek() is called:
- If the cache is empty, pull one element from the source and store it.
- Return the cached element without advancing.
When next() is called:
- If the cache is full, return the cached element, clear the cache, and mark it empty.
- Otherwise, delegate to the source.
hasNext() returns true if the cache is full or the source has more elements.
Complexity: O(1) per operation, O(1) extra space.
Extension 2: Filtering
The tricky part: hasNext() cannot answer "is there a matching element?" without actually finding it. The solution is to do the work inside hasNext() and cache the result.
Maintain a cached element and a flag indicating whether the cache is full. Define an internal advance method:
- While the cache is empty and the source has elements, pull the next element.
- If it satisfies the predicate, store it in the cache and set the flag.
Call this advance method at the start of hasNext(). If the cache is full after advancing, return true. Otherwise, return false.
When next() is called, check hasNext() first (which fills the cache if needed), then return the cached element and clear the cache.
Complexity: Amortized O(1) per yielded element. A single hasNext() call may skip k non-matching elements, but each source element is examined exactly once.
Extension 3: Flattening
Accept an iterator of iterators (the "outer" iterator). Maintain a reference to the current inner iterator.
Define an internal advance method:
- Loop while the current inner iterator is either null or exhausted.
- If the outer iterator has more elements, pull the next inner iterator and assign it to
current. - If the outer iterator is exhausted, stop.
The loop (not just a single if-check) is critical. If several consecutive inner iterators are empty, the loop will skip all of them in one advance call.
Call the advance method inside hasNext(). After advancing, return true if the current inner iterator has elements, false otherwise.
When next() is called, first call hasNext() to ensure the current inner iterator is valid, then delegate to current.next().
Complexity: Amortized O(1). Skipping k empty inner iterators in one call is fine because each inner iterator is visited at most once.
Edge cases
- Empty input:
hasNext()returns false immediately,next()throws. - Exhaustion: calling
next()after the iterator is exhausted must throw an exception, not return null or loop. - Idempotent
hasNext(): calling it ten times without callingnext()must produce the same result each time. - Peek and next interleaved:
peek()followed bynext()must return the same element. Twopeek()calls in a row must return the same element. - Filter matching nothing: the iterator is valid but immediately exhausted.
- Flatten over all-empty inner iterators: should exhaust without yielding any elements.
- Invalid range:
step = 0should be rejected at construction time.
Implementation outline (Python)
from abc import ABC, abstractmethod
class NoElementError(Exception):
pass
class Iterator(ABC):
@abstractmethod
def has_next(self) -> bool:
pass
@abstractmethod
def next(self):
pass
class ArrayIterator(Iterator):
def __init__(self, items):
self._items = items
self._index = 0
def has_next(self):
return self._index < len(self._items)
def next(self):
if not self.has_next():
raise NoElementError("Iterator exhausted")
value = self._items[self._index]
self._index += 1
return value
class RangeIterator(Iterator):
def __init__(self, start, stop, step=1):
if step == 0:
raise ValueError("Step cannot be zero")
self._current = start
self._stop = stop
self._step = step
def has_next(self):
if self._step > 0:
return self._current < self._stop
else:
return self._current > self._stop
def next(self):
if not self.has_next():
raise NoElementError("Range exhausted")
value = self._current
self._current += self._step
return value
class PeekableIterator(Iterator):
def __init__(self, source: Iterator):
self._source = source
self._cache = None
self._cache_full = False
def peek(self):
if not self._cache_full:
self._cache = self._source.next()
self._cache_full = True
return self._cache
def has_next(self):
return self._cache_full or self._source.has_next()
def next(self):
if self._cache_full:
value = self._cache
self._cache = None
self._cache_full = False
return value
return self._source.next()
class FilteredIterator(Iterator):
def __init__(self, source: Iterator, predicate):
self._source = source
self._predicate = predicate
self._cache = None
self._cache_full = False
def _advance(self):
while not self._cache_full and self._source.has_next():
candidate = self._source.next()
if self._predicate(candidate):
self._cache = candidate
self._cache_full = True
break
def has_next(self):
self._advance()
return self._cache_full
def next(self):
if not self.has_next():
raise NoElementError("No matching elements remain")
value = self._cache
self._cache = None
self._cache_full = False
return value
class FlattenedIterator(Iterator):
def __init__(self, outer: Iterator):
self._outer = outer
self._current = None
def _advance(self):
while (self._current is None or not self._current.has_next()):
if not self._outer.has_next():
self._current = None
return
self._current = self._outer.next()
def has_next(self):
self._advance()
return self._current is not None and self._current.has_next()
def next(self):
if not self.has_next():
raise NoElementError("All inner iterators exhausted")
return self._current.next()
Testing strategy
Write tests for each iterator type:
- Base iterators: empty, single element, multiple elements, exhaustion
- Peeking: peek without next, peek then next, multiple peeks, peek on empty
- Filtering: all match, none match, some match, empty source
- Flattening: all inner iterators empty, some empty, outer iterator empty, mixed
Run these tests to validate correctness before presenting the solution.
Common mistakes
- Forgetting the loop in flattening: using
ifinstead ofwhilemeans only one empty inner iterator is skipped per advance call. - Calling
next()insidehasNext(): this violates the idempotency contract. - Not caching in filtering: recomputing the next match on every
hasNext()call is incorrect ifhasNext()is called multiple times. - Returning null instead of throwing: the contract requires an exception when the iterator is exhausted.
Complexity summary
| Iterator | Time per operation | Space |
|---|---|---|
| Array, Range | O(1) | O(1) |
| Peekable | O(1) | O(1) |
| Filtered | O(1) amortized | O(1) |
| Flattened | O(1) amortized | O(1) beyond inputs |
All implementations avoid copying the underlying data and maintain at most one element of lookahead.