The Peeking Iterator problem asks you to design a wrapper iterator that adds a peek() method to an existing iterator. peek() returns the next element without advancing the iterator, while next() and hasNext() work normally. This coding problem tests iterator design patterns. The array, design, and iterator interview pattern is demonstrated.
Apple, Meta, Yahoo, TikTok, and Google ask this because it tests design skills — specifically how to cache a "lookahead" value without consuming it permanently. This pattern appears in parsers, tokenizers, and streaming systems where look-ahead is needed.
Cache the next value. Store peeked_value and has_peeked flag. peek(): if not has_peeked, call iterator.next(), store result in peeked_value, set has_peeked=True. Return peeked_value. next(): if has_peeked, clear cache and return peeked_value; else call iterator.next(). hasNext(): return has_peeked OR iterator.hasNext().
Iterator over [1,2,3].
has_peeked in hasNext() (if iterator is exhausted but peeked value exists, hasNext must return true).has_peeked flag in next() after returning cached value.iterator.next() in peek() every time (should cache after first call).The Peeking Iterator is a classic design pattern — the "lookahead cache." The key insight: one level of caching (peeked_value + flag) is sufficient. This pattern appears in Java's PushbackInputStream, Python's itertools.chain, and any parser needing one-token lookahead. Practice implementing it cleanly: three methods with correct interaction between the cache and the underlying iterator.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| RLE Iterator | Medium | Solve | |
| Zigzag Iterator | Medium | Solve | |
| Flatten 2D Vector | Medium | Solve | |
| Design Compressed String Iterator | Easy | Solve | |
| Encode and Decode Strings | Medium | Solve |