0284. Peeking Iterator

284. Peeking Iterator #

Problem #

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next().

Example:

Assume that the iterator is initialized to the beginning of the list: [1,2,3].

Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. 
You call next() the final time and it returns 3, the last element. 
Calling hasNext() after that should return false.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Problem Summary #

Given an iterator class interface, which contains two methods: next() and hasNext(). Design and implement a peeking iterator that supports the peek() operation – its essence is to peek() at the element that would originally be returned by the next() method.

peek() means to take a look. Secretly look at what the next element is, but it is not accessed by next().

Solution Ideas #

  • Simple problem. Store 2 variables inside PeekingIterator: one is the next element value, and the other is whether there is a next element. During the next() and hasNext() operations, access these 2 saved variables. The peek() operation is also relatively simple: determine whether there is a next element, and if there is, return that element value. This implements the functionality of not moving the iteration pointer. If the next element value is not saved, meaning there has been no peek(), the next() operation continues to move the pointer backward and reads the following element.
  • Here, whether there is a next element value is reused to determine the logic for not moving the pointer in the hasNext() and peek() operations.

Code #

package leetcode

//Below is the interface for Iterator, which is already defined for you.

type Iterator struct {
}

func (this *Iterator) hasNext() bool {
	// Returns true if the iteration has more elements.
	return true
}

func (this *Iterator) next() int {
	// Returns the next element in the iteration.
	return 0
}

type PeekingIterator struct {
	nextEl int
	hasEl  bool
	iter   *Iterator
}

func Constructor(iter *Iterator) *PeekingIterator {
	return &PeekingIterator{
		iter: iter,
	}
}

func (this *PeekingIterator) hasNext() bool {
	if this.hasEl {
		return true
	}
	return this.iter.hasNext()
}

func (this *PeekingIterator) next() int {
	if this.hasEl {
		this.hasEl = false
		return this.nextEl
	} else {
		return this.iter.next()
	}
}

func (this *PeekingIterator) peek() int {
	if this.hasEl {
		return this.nextEl
	}
	this.hasEl = true
	this.nextEl = this.iter.next()
	return this.nextEl
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文