Practice Peeking Iterator
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
PeekingIterator wraps an existing integer iterator. next() consumes and returns the next value; hasNext() reports whether one remains; peek() returns the next value without consuming it. next and peek are invoked only when valid. Practice approach: Buffer one upcoming value and track its presence separately. peek fills the buffer only if empty; next consumes the buffer before delegating to the underlying iterator. Repeated peeks must return the same value. The wrapper uses O(1) extra space and adds O(1) work per call. A separate presence flag also permits generic values without reserving a sentinel.
Source: Peeking Iterator on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
["PeekingIterator","peek","peek","next","hasNext","next","hasNext"] [[[4,7]],[],[],[],[],[],[]]
[null,4,4,4,true,7,false]
Two peeks leave 4 unconsumed; only next advances the underlying sequence.
Constraints
Related LeetCode Problems
Practice more problems similar to Peeking Iterator.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.