LeetCode 284: Peeking Iterator Solution
Master LeetCode problem 284 (Peeking Iterator), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To implement a PeekingIterator class that supports the peek operation, we can store the current element in a variable and update it accordingly. When peek is called, we return the stored element without moving the iterator. We will also maintain a boolean flag to keep track of whether a peek has been performed or not.
Time Complexity
next: O(1)peek: O(1)hasNext: O(1)
Space Complexity
- O(1)
Solution Code
import java.util.Iterator;
class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iterator;
private Integer nextElement;
private boolean hasPeeked;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
if (iterator.hasNext()) {
nextElement = iterator.next();
hasPeeked = false;
}
}
public Integer peek() {
if (!hasPeeked) {
nextElement = iterator.next();
hasPeeked = true;
}
return nextElement;
}
@Override
public Integer next() {
if (!hasPeeked) {
return iterator.next();
}
Integer result = nextElement;
hasPeeked = false;
nextElement = null;
return result;
}
@Override
public boolean hasNext() {
return hasPeeked || iterator.hasNext();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 284 (Peeking Iterator)?
This page provides optimized solutions for LeetCode problem 284 (Peeking Iterator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 284 (Peeking Iterator)?
The time complexity for LeetCode 284 (Peeking Iterator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 284 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 284 in Java, C++, or Python.