Question

Formatted question description: https://leetcode.ca/all/284.html

 284	Peeking Iterator

 Given an Iterator class interface with methods: preFetch() and hasNext(),
 design and implement a PeekingIterator that support the peek() operation --
    it essentially peek() at the element that will be returned by the preFetch call to preFetch().


 Here is an example.
 Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].
 Call preFetch() gets you 1, the first element in the list.
 Now you call peek() and it returns 2, the preFetch element. Calling preFetch() after that still return 2.
 You call preFetch() the final time and it returns 3, the last element. Calling hasNext() after that should return false.


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

 @tag-design

Algorithm

You can define a variable preFetch to save the next value, use a bool variable to mark whether the next value is saved, and then call some of the original member functions.

Code

Java

  • import java.util.Iterator;
    
    class PeekingIterator implements Iterator<Integer> {
        private Integer preFetch = null;
        private Iterator<Integer> iterator;
    
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
            this.iterator = iterator;
            if (this.iterator.hasNext())
                preFetch = this.iterator.next();
        }
    
        // Returns the preFetch element in the iteration without advancing the iterator.
        public Integer peek() {
            return preFetch;
        }
    
        // hasNext() and preFetch() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            Integer toReturn = preFetch;
            preFetch = iterator.hasNext() ? iterator.next() : null;
            return toReturn;
        }
    
        @Override
        public boolean hasNext() {
            return preFetch != null;
        }
    }
    
    
    
    /////////////////////////////////
    
    // I used 2 flags to indicate if it's end of an iterator
    // but, Integer can be noll, but int cannot be null. So, set preFetch to be null will solve the problem
    public class Peeking_Iterator {
    
        // Java Iterator interface reference:
        // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
        class PeekingIterator implements Iterator<Integer> {
    
            int preFetch;
            Iterator<Integer> iterator;
            boolean isIteratorEmpty;
            boolean isLastPrefetchPopped;
    
            public PeekingIterator(Iterator<Integer> iterator) {
    
                this.iterator = iterator;
    
                // initialize any member here.
                if (this.iterator.hasNext()) {
                    preFetch = this.iterator.next();
                } else {
                    isIteratorEmpty = true;
                    isLastPrefetchPopped = true;
                }
            }
    
            // Returns the preFetch element in the iteration without advancing the iterator.
            public Integer peek() {
    
                if (isIteratorEmpty && isLastPrefetchPopped) {
                    // cannot peek, throw some exception here
                    return null;
                } else {
                    return preFetch;
                }
            }
    
            // hasNext() and preFetch() should behave the same as in the Iterator interface.
            // Override them if needed.
            @Override
            public Integer next() {
    
                if (isIteratorEmpty && isLastPrefetchPopped) {
                    // cannot peek, throw some exception here
                    return null;
                }
    
                int toReturn = preFetch;
    
                if (this.iterator.hasNext()) {
                    preFetch = this.iterator.next();
                } else {
                    isIteratorEmpty = true;
                    isLastPrefetchPopped= true;
                }
    
                return preFetch;
            }
    
            @Override
            public boolean hasNext() {
                if (isIteratorEmpty && isLastPrefetchPopped) {
                    return false;
                } else {
                    return true;
                }
            }
        }
    
    }
    
  • Todo
    
  • # 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.iter = iterator
        self.nextElem = None
    
      def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if self.nextElem:
          return self.nextElem
        if self.iter.hasNext():
          self.nextElem = self.iter.next()
        return self.nextElem
    
      def next(self):
        """
        :rtype: int
        """
        ret = self.nextElem
    
        if self.nextElem:
          self.nextElem = None
          return ret
    
        return self.iter.next()
    
      def hasNext(self):
        """
        :rtype: bool
        """
        return (self.nextElem is not None) or self.iter.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].
    
    

All Problems

All Solutions