Python solution with detailed explanation

  • 0


    Peeking Iterator


    • Peeking requires us to cache one step ahead.
    • Maintain a self.cache and a self.status variable.
    • self.status is returned for hasNext. Initialize it in constructor. First call can be for peek().
    • Update the status variable only in next, not in peek.
    class PeekingIterator(object):
        def __init__(self, iterator):
            Initialize your data structure here.
            :type iterator: Iterator
            self.iterator, self.cache = iterator, None
            self.status = iterator.hasNext()
        def peek(self):
            Returns the next element in the iteration without advancing the iterator.
            :rtype: int
            if self.cache is None:
                self.cache =
            return self.cache
        def next(self):
            :rtype: int
            x = self.cache if self.cache else
            self.cache, self.status = None, self.iterator.hasNext()
            return x
        def hasNext(self):
            :rtype: bool
            return self.status

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.