Skip to content

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.

Medium#284
LeetCode Problem

Peeking Iterator

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

Input
["PeekingIterator","peek","peek","next","hasNext","next","hasNext"]
[[[4,7]],[],[],[],[],[],[]]
Output
[null,4,4,4,true,7,false]
Explanation

Two peeks leave 4 unconsumed; only next advances the underlying sequence.

Constraints

1 <= nums.length <= 1000
1 <= nums[i] <= 1000
At most 1000 total method calls.
next and peek calls are valid.

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.