Peeking Iterator
Medium · Design · Array · Design · Iterator
Problem
An iterator hands out a sequence one element at a time: next() returns the next element and moves past it, and hasNext() says whether any are left. Design a PeekingIterator that adds one more operation, peek(), which returns the next element without moving past it.
Implement the class:
- PeekingIterator(nums) starts before the first element of nums. Treat nums as a stream: read it front to back, the way a plain iterator would (in Python, iter(nums)), rather than by index.
- peek() returns the next element without consuming it.
- next() returns the next element and moves past it.
- hasNext() returns true if any elements are left.
Every call to peek() and next() is made while an element is left. Calls are given as two lists: the operation names, and each call's arguments.
Examples
Input: operations = ["PeekingIterator", "next", "peek", "next", "next", "hasNext"] arguments = [[[1, 2, 3]], [], [], [], [], []] Output: [null, 1, 2, 2, 3, false]
peek() sees 2 and the following next() still returns 2.
Input: operations = ["PeekingIterator", "peek", "peek", "next", "hasNext"] arguments = [[[7]], [], [], [], []] Output: [null, 7, 7, 7, false]
Peeking twice returns the same element and consumes nothing.
Constraints
- 1 <= len(nums) <= 1000
- 1 <= nums[i] <= 1000
- At most 1000 calls to peek, next and hasNext
- peek and next are only called while an element is left
Approaches
- Copy everything into a queue — time O(n) to build, O(1) per call, space O(n)
Follow-up
To work with any element type, the cache needs a separate "has a value" flag rather than a sentinel such as None, because None may itself be an element. The same one-element lookahead is how tokenizers let a parser peek at the next token.
Related problems
Start free on Cariara · Coding problems · System design studio