Watch 10 video solutions for Peeking Iterator, a medium level problem involving Array, Design, Iterator. This walkthrough by NeetCode has 49,532 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.
Implement the PeekingIterator class:
PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator.int next() Returns the next element in the array and moves the pointer to the next element.boolean hasNext() Returns true if there are still elements in the array.int peek() Returns the next element in the array without moving the pointer.Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.
Example 1:
Input ["PeekingIterator", "next", "peek", "next", "next", "hasNext"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 2, 2, 3, false] Explanation PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,2,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1000next and peek are valid.1000 calls will be made to next, hasNext, and peek.Follow up: How would you extend your design to be generic and work with all types, not just integer?
Problem Overview: Design a wrapper around an existing iterator that supports an additional peek() operation. The challenge is returning the next element without advancing the underlying iterator while still supporting the standard next() and hasNext() behavior.
The base iterator already provides sequential access. Your job is to extend it so that you can preview the upcoming value. The key difficulty is ensuring that calling peek() does not consume the element while keeping all operations efficient.
Approach 1: Using Internal Buffer Variable (O(1) time, O(1) space)
Maintain a single buffered variable that always stores the next element from the iterator. During initialization, call next() on the underlying iterator and store the value in this buffer. The peek() method simply returns the buffered value without modifying the iterator state.
When next() is called, return the buffered value and immediately fetch the next element from the underlying iterator to refresh the buffer. If the iterator has no more elements, mark the buffer as empty. hasNext() checks whether the buffer currently holds a value. Each operation runs in constant time and uses only one extra variable.
This approach works well in languages like Python and Java where wrapping an existing iterator object is straightforward. The design keeps state management simple and avoids repeated checks on the underlying data structure.
Approach 2: Iterator with Future Look-ahead (O(1) time, O(1) space)
This design also stores the upcoming element but treats it as a "future" pointer. During construction, advance the underlying iterator once and store the value as the next candidate. The peek() method returns this value directly.
When next() is called, return the stored value and advance the underlying iterator again to update the future pointer. If the iterator has no remaining elements, mark the future pointer as invalid. hasNext() checks whether the future pointer exists.
This pattern is common in system design questions involving design of iterators or streaming APIs. It avoids modifying the original array or collection and keeps operations constant time.
Recommended for interviews: The buffered look-ahead design is the expected solution. Interviewers want to see that you maintain a cached next value so peek() does not advance the iterator. A naive implementation that repeatedly copies elements or re-traverses the structure would break iterator semantics and increase complexity. Demonstrating a constant-time wrapper around the iterator shows strong understanding of iterator design.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Internal Buffer Variable | O(1) per operation | O(1) | Standard iterator wrapper design in Python or Java |
| Iterator with Future Look-ahead | O(1) per operation | O(1) | Clean design for C++ or C# iterators where a cached next element simplifies peek behavior |