Peeking Iterator - Problem
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and next operations.
Implement the PeekingIterator class:
PeekingIterator(Iterator<int> nums)Initializes the object with the given integer iteratoriterator.int next()Returns the next element in the array and moves the pointer to the next element.boolean hasNext()Returnstrueif 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.
Input & Output
Example 1 — Basic Operations
$
Input:
nums = [1,2,3], operations = ["next", "peek", "next", "next", "hasNext"]
›
Output:
[1, 2, 2, 3, false]
💡 Note:
next() returns 1 and advances. peek() returns 2 without advancing. next() returns 2 and advances. next() returns 3 and advances. hasNext() returns false as no more elements.
Example 2 — Multiple Peeks
$
Input:
nums = [1,2], operations = ["peek", "peek", "next", "hasNext"]
›
Output:
[1, 1, 1, true]
💡 Note:
peek() returns 1 without advancing (called twice). next() returns 1 and advances. hasNext() returns true as element 2 remains.
Example 3 — Empty Check
$
Input:
nums = [1], operations = ["next", "hasNext", "peek"]
›
Output:
[1, false, null]
💡 Note:
next() returns 1 and advances. hasNext() returns false. peek() on empty iterator behavior varies by implementation.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
- At most 1000 calls will be made to next, hasNext, and peek
Visualization
Tap to expand
Understanding the Visualization
1
Input
Iterator with [1,2,3] and operations to perform
2
Process
Peek shows next element without moving, next advances
3
Output
Results array based on operations performed
Key Takeaway
🎯 Key Insight: Use a buffer to cache the next element, enabling peek operations in O(1) time without affecting iterator state
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code