Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Peeking Iterator

mediumdesigniterator

Problem

You are given an iterator object that exposes hasNext() and next(). Wrap it in a class PeekingIterator that additionally supports peek(), which returns the element that the next call to next() will return, without consuming it. The wrapper must preserve the semantics of hasNext() and next(), and must not call the underlying next() more than once per element.

  • The sequence holds at most about a thousand elements.
  • Elements can be any integer, including negative values and zero; do not assume any value is unused.
  • Callers may call peek() any number of times in a row.

Examples

  • Underlying sequence [7, 8, 9]: next() → 7; peek() → 8; peek() → 8; next() → 8; next() → 9; hasNext() → False.
  • Underlying [4]: peek() → 4; hasNext() → True; next() → 4; hasNext() → False.
  • Underlying [0, -1]: peek() → 0; next() → 0; peek() → -1. Zero and negatives are ordinary values and must not be confused with "nothing buffered".

Hints

  1. To know what next() will return without consuming it, you have to have already fetched it. Where do you keep it?
  2. A single buffered element plus a flag for "is the buffer full" is enough. Every method must be written in terms of that buffer.
  3. Eagerly load the buffer in the constructor and after each next(), so hasNext is simply "is the buffer full" and peek is "return the buffer".

Last reviewed 8 September 2026