LeetCode 284. Peeking Iterator

Post by ailswan Dec. 13, 2023

284. Peeking Iterator

Problem Statement

link: LeetCode.cn LeetCode

Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the array and moves the pointer to the next element. boolean hasNext() Returns true if there are still elements in the array. int peek() Returns the next element in the array without moving the pointer. Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

Example:

Input: ["PeekingIterator", "next", "peek", "next", "next", "hasNext"][[[1, 2, 3]], [], [], [], [], []] Output: [null, 1, 2, 2, 3, false]

Solution Approach

The PeekingIterator class initializes with an iterator, and its methods (next, peek, and hasNext) provide functionality to retrieve the next element, peek at the next element without advancing the iterator, and check if there are remaining elements, respectively, utilizing a variable (peeknum) to store the next element.

Algorithm

Implement

    class PeekingIterator:
    def __init__(self, iterator):
    """
    Initialize your data structure here.
    :type iterator: Iterator
    """
    self.it = iterator
    self.peeknum = self.it.next() if self.it.hasNext() else None
    

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

def next(self):
    """
    :rtype: int
    """
    ret = self.peeknum
    self.peeknum = self.it.next() if self.it.hasNext() else None
    return ret
    

def hasNext(self):
    """
    :rtype: bool
    """
    return self.peeknum is not None