#284
Medium Algorithms Peeking iterator
Array Design Iterator
61.3% acceptance
Jan 13, 2026
1908
1052
Design an iterator that supports the peek operation on an existing iterator
in addition to the hasNext and the next operations.
Solution
C++
Time O(1)
Space O(1)
class PeekingIterator : public Iterator {
int _next;
bool _hasNext;
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
_hasNext = Iterator::hasNext();
if (_hasNext) _next = Iterator::next();
}
int peek() {
return _next;
}
int next() {
int val = _next;
_hasNext = Iterator::hasNext();
if (_hasNext) _next = Iterator::next();
return val;
}
bool hasNext() const {
return _hasNext;
}
};