Peeking Iterator
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
- To know what
next()will return without consuming it, you have to have already fetched it. Where do you keep it? - A single buffered element plus a flag for "is the buffer full" is enough. Every method must be written in terms of that buffer.
- Eagerly load the buffer in the constructor and after each
next(), sohasNextis simply "is the buffer full" andpeekis "return the buffer".
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.