Leetcode 284. Peeking Iterator
284. Peeking Iterator
Given an Iterator class interface with methods: next()
and hasNext()
, design and implement a PeekingIterator that supports the peek()
operation.
Implement the PeekingIterator class:
PeekingIterator(Iterator<E> iterator)
Initializes the object with the given iterator.E peek()
Returns the next element in the iteration without advancing the iterator.E next()
Returns the next element and advances the iterator.boolean hasNext()
Returns true
if the iteration has more elements.E
.peek()
is called when there are no more elements?
peek()
or next()
if hasNext()
is false
.To implement the PeekingIterator
class, we need to store the next element so that the peek()
function can return it without advancing the iterator. This requires maintaining an internal state and ensuring the iterator’s position is only advanced when next()
is called.
Here’s a step-by-step strategy:
peek()
.peek()
Method: Return the preloaded element without advancing the iterator.next()
Method: Return the preloaded element and fetch the next element for future operations.hasNext()
Method: Simply check if the preloaded element (or cache) is available.import java.util.Iterator;
class PeekingIterator<E> implements Iterator<E> {
private Iterator<E> iterator;
private E nextElement;
private boolean hasNext;
public PeekingIterator(Iterator<E> iterator) {
this.iterator = iterator;
if (iterator.hasNext()) {
nextElement = iterator.next();
hasNext = true;
} else {
hasNext = false;
}
}
public E peek() {
return nextElement;
}
@Override
public E next() {
E result = nextElement;
if (iterator.hasNext()) {
nextElement = iterator.next();
} else {
hasNext = false;
}
return result;
}
@Override
public boolean hasNext() {
return hasNext;
}
}
PeekingIterator
): O(1) – Initializing and preloading the first element is done in constant time.peek
): O(1) – Simply returns the preloaded element.next
): O(1) – Returns the preloaded element and fetches the next one in constant time.hasNext
): O(1) – Simply returns the boolean flag.The space complexity is O(1) since we are using a minimal amount of extra space for storing the element and a boolean flag.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?