284.Peeking Iterator

Tags: [iterator], [data_structure]

Link: https://leetcode.com/problems/peeking-iterator/#/description

Given an Iterator class interface with methods:next()andhasNext(), design and implement a PeekingIterator that support thepeek()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].

Callnext()gets you 1, the first element in the list.

Now you callpeek()and it returns 2, the next element. Callingnext()after thatstillreturn 2.

You callnext()the final time and it returns 3, the last element. CallinghasNext()after that should return false.

Hint:

  1. Think of "looking ahead". You want to cache the next element.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek()before next()vs next()before peek().
  4. For a clean implementation, check out Google's guava library source code.

Follow up: How would you extend your design to be generic and work with all types, not just integer?


Better Solution:

# 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.iterator = iterator
        self.head = None


    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if self.head:
            return self.head

        self.head = self.iterator.next()
        return self.head


    def next(self):
        """
        :rtype: int
        """
        if self.head:
            elem = self.head
            self.head = None
            return elem

        return self.iterator.next()


    def hasNext(self):
        """
        :rtype: bool
        """
        return self.head is not None 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].

Solution:

# 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.iterator = iterator
        self.queue = []


    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if self.queue:
            return self.queue[0]

        self.queue.append(self.iterator.next())
        return self.queue[0]


    def next(self):
        """
        :rtype: int
        """
        if self.queue:
            return self.queue.pop(0)

        return self.iterator.next()


    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.queue) > 0 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].

Note:

  • In Python, if we do "return self.queue or self.iterator.hasNext()", if there is elements in self.queue, it will return [elem1, elem2, elem3...]

results matching ""

    No results matching ""