Peeking Iterator LeetCode Solution

Last updated on January 5th, 2025 at 01:19 am

Here, we see Peeking Iterator LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Design

Companies

Apple, Google, Yahoo

Level of Question

Medium

Peeking Iterator LeetCode Solution

Peeking Iterator LeetCode Solution

1. Problem Statement

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<int> 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 1:
Input [“PeekingIterator”, “next”, “peek”, “next”, “next”, “hasNext”] [[[1, 2, 3]], [], [], [], [], []]
Output [null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

2. Coding Pattern Used in Solution

The provided code implements a “Peeking Iterator” design pattern. This is not directly related to any of the listed patterns (e.g., Sliding Window, Two Pointers, etc.). Instead, it falls under the Iterator Design Pattern. The goal of this pattern is to enhance the functionality of an existing iterator by adding the ability to “peek” at the next element without advancing the iterator.

3. Code Implementation in Different Languages

3.1 Peeking Iterator C++

class PeekingIterator : public Iterator {
private:
    int m_next;
    bool m_hasnext;
public:
	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
	    m_hasnext = Iterator::hasNext();
	    if (m_hasnext) m_next = Iterator::next();
	}

	int peek() {
        return m_next;
	}

	int next() {
	    int t = m_next;
	    m_hasnext = Iterator::hasNext();
	    if (m_hasnext) m_next = Iterator::next();
	    return t;
	}

	bool hasNext() const {
	    return m_hasnext;
	}
};

3.2 Peeking Iterator Java

class PeekingIterator implements Iterator<Integer> {  
    private Integer next = null;
    private Iterator<Integer> iter;

    public PeekingIterator(Iterator<Integer> iterator) {
        iter = iterator;
        if (iter.hasNext())
            next = iter.next();
    }
    
    public Integer peek() {
        return next; 
    }

    public Integer next() {
        Integer res = next;
        next = iter.hasNext() ? iter.next() : null;
        return res; 
    }

    public boolean hasNext() {
        return next != null;
    }
}

3.3 Peeking Iterator JavaScript

var PeekingIterator = function(iterator) {
    this.peeked = null;
    this.iterator = iterator;
};

PeekingIterator.prototype.peek = function() {
    if(this.peeked!==null){
        return this.peeked;
    }
    if(this.iterator.hasNext()!==false){
        this.peeked = this.iterator.next();
    }
    return this.peeked; 
};

PeekingIterator.prototype.next = function() {
    var val = "";
    if(this.peeked!==null){
        val = this.peeked;
        this.peeked = null;
        return val;
    }
    return this.iterator.next();
};

PeekingIterator.prototype.hasNext = function() {
    if(this.peeked!==null){
        return true;
    }
    return this.iterator.hasNext();
};

3.4 Peeking Iterator Python

class PeekingIterator(object):
    def __init__(self, iterator):
        self.iter = iterator
        self.temp = self.iter.next() if self.iter.hasNext() else None

    def peek(self):
        return self.temp

    def next(self):
        ret = self.temp
        self.temp = self.iter.next() if self.iter.hasNext() else None
        return ret

    def hasNext(self):
        return self.temp is not None

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(1)O(1)
JavaO(1)O(1)
JavaScriptO(1)O(1)
PythonO(1)O(1)

The PeekingIterator enhances an existing iterator by adding the ability to “peek” at the next element without advancing the iterator. It achieves this by pre-fetching the next element during initialization and updating the state during each next() call. All operations (peek()next()hasNext()) are constant time, and the space usage is minimal. This implementation is efficient and adheres to the Iterator Design Pattern.

Scroll to Top