leetCode Question: Peeking Iterator

Peeking Iterator

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().

Here is an 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.

Analysis:

This is a design problem, which requires you familiar with the Object-Oriented basics.

In C++, calling base class methods within derived class can be done using "baseclassName::baseclassMethod()"
In python, usually we use "super(BaseClassName, self)" to do so. However, in this problem, the python interface does NOT provide the inheritance of class Iterator, but use the Iterator as a class member, therefore just call a member's function is enough.

Back to the question, we have to notice that:

  • The peek() method could be called multiple times but we can only go next() at the first time.
  • The next() method could be called before or after peek(). We need a flag and a value to store the state if the peek() method has been called or not (as well as the value).
  • To check the hasNext(), we have to check the stored peek value, because if we peek() the last value, it is called the next() method of base class resulting in the last value is poped from the array but only exists in our stored peeked_value. So the hasNext() method of baseclass will return a false, but actually we just "peeked" the next value.

Code (C++):

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
struct Data;
Data* data;
public:
Iterator(const vector<int>& nums);
Iterator(const Iterator& iter);
virtual ~Iterator();
// Returns the next element in the iteration.
int next();
// Returns true if the iteration has more elements.
bool hasNext() const;
};
class PeekingIterator : public Iterator {
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
int peekedVal = NULL;
bool hasPeeked = false;
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
if (!hasPeeked){
peekedVal = Iterator::next();
hasPeeked = true;
}
return peekedVal;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
if (!peek()){
return Iterator::next();
}
int tmp = peekedVal;
peekedVal = NULL;
hasPeeked = false;
return tmp;
}
bool hasNext() const {
return hasPeeked || Iterator::hasNext();
}
private:
int peekedVal;
bool hasPeeked;
};

Code (Python):

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.is_peeked = False
self.peeked_val = None
self.iterator = iterator
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.is_peeked:
self.peeked_val = self.iterator.next()
self.is_peeked = True
return self.peeked_val;
def next(self):
"""
:rtype: int
"""
if not self.is_peeked:
return self.iterator.next()
tmp = self.peeked_val
self.peeked_val = None
self.is_peeked = False
return tmp
def hasNext(self):
"""
:rtype: bool
"""
return self.is_peeked or self.iterator.hasNext()
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].

2 comments: