Magicsheet logo

Peeking Iterator

Medium
23.8%
Updated 6/1/2025

Peeking Iterator

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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().

Example explanation

Iterator over [1,2,3].

  • peek(): cache 1, return 1. has_peeked=True.
  • peek(): already cached, return 1.
  • next(): return cached 1, has_peeked=False.
  • next(): call iterator.next(), return 2.
  • hasNext(): iterator has 3, return true.
  • next(): return 3.
  • hasNext(): return false.

Common mistakes candidates make

  • Not checking has_peeked in hasNext() (if iterator is exhausted but peeked value exists, hasNext must return true).
  • Not clearing has_peeked flag in next() after returning cached value.
  • Calling iterator.next() in peek() every time (should cache after first call).
  • Incorrect initialization (peeked_value not set until first peek).

Interview preparation tip

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.

Similar Questions