KatInterview

Design a Lazy Iterator Pipeline with Range and Combinators

Data Structure DesignModel answer
MediumModel answerData Structure Designiteratorslazy-evaluationfunctional-programming

Last 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) where step can 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 element
  • filter(pred) — keep only elements satisfying a predicate
  • zip(*others) — combine multiple iterators element-wise
  • take(n) — yield at most n elements
  • drop(n) — skip the first n elements
  • chain(*others) — concatenate multiple iterators sequentially

Peekable wrapper:

  • peek() — return the next element without consuming it
  • hasNext() — check if more elements are available
  • Discuss whether reset() or rewind() 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'