KatInterview

Build Iterator Abstractions and Composed Traversals

Data Structure DesignModel answer
MediumModel answerData Structure Designiteratorsinterface-designlazy-evaluation

Last 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 otherwise
  • next(): 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

  1. Collection iterator: traverses a backing array or list without copying it
  2. 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:

  1. Peeking: add a peek() method that returns the next element without consuming it
  2. Filtering: wrap an iterator and a predicate function; only yield elements that satisfy the predicate
  3. 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