Python Solution, constant space, 48ms


  • 0
    M
    class PeekingIterator(object):
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.iterator = iterator
        self.peekstep = 0
        self.nextstep = 0
        self.peeknum = None
            
        
    
    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if self.nextstep >= self.peekstep and self.iterator.hasNext():
            self.peekstep = self.nextstep + 1
            self.peeknum = self.iterator.next()
        return self.peeknum
    
    def next(self):
        """
        :rtype: int
        """
        if self.peekstep > self.nextstep:
            self.nextstep += 1
            return self.peeknum
        else:
            self.nextstep += 1
            return self.iterator.next()
    
    
    
    def hasNext(self):
        """
        :rtype: bool
        """
        if self.nextstep < self.peekstep:
            return True
        return self.iterator.hasNext()

  • 0
    M

    I don't think its belong to medium problems


Log in to reply
 

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