Python solution with detailed explanation


  • 0
    G

    Solution

    Peeking Iterator https://leetcode.com/problems/peeking-iterator/

    Algorithm

    • 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 = self.iterator.next()
            return self.cache
    
        def next(self):
            """
            :rtype: int
            """
            x = self.cache if self.cache else self.iterator.next()
            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.