Implement custom iterator classes
CoinbaseSoftware Engineer · OnsiteLast updated
This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Implement custom iterator classes states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Question
In a blank coding environment (no IDE assistance, no autocomplete), implement an iterator abstraction entirely from scratch. The interviewer typically asks for this in Java, but the same exercise generalizes to any language with an explicit iterator protocol.
- Define the iterator interface manually. Write the
Iteratorinterface yourself (do not import the language's built-in one). At minimum it should exposehasNext()(is there another element?) andnext()(return the next element and advance). - Implement two concrete iterator classes that implement your interface. For example, one that iterates over a simple backing collection (array or list), and a second one with different traversal semantics (such as a range/generator-style iterator, or one composed over another iterator).
- Satisfy three follow-up sub-problems. During the round the interviewer adds three incremental requirements on top of the basic iterators — typically additional traversal features (e.g.
peek()without advancing, aremove()operation, filtering, or flattening/concatenating multiple iterators) or performance/laziness guarantees (e.g. O(1)next(), lazy evaluation, no full-collection copy). - Write runnable unit tests from scratch that validate each iterator and each follow-up requirement, including edge cases (empty collection, single element, exhausting the iterator, calling
next()past the end).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.