KatInterview

284. Peeking Iterator

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge is to augment a standard Iterator with a peek() method. peek() allows us to look at the next element in the sequence without advancing the iterator's position. A standard iterator only provides next() (which retrieves the next element and advances the position) and hasNext() (which checks for the existence of a next element). We must implement this new functionality using only the methods provided by the base iterator.

Solution

Peeking Iterator in Python

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
#     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:
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.iterator = iterator
        self.peeked_element = None # This will cache the next element.
        
        # Pre-fetch the first element from the iterator to initialize our cache.
        if self.iterator.hasNext():
            self.peeked_element = self.iterator.next()

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

    def next(self):
        """
        :rtype: int
        """
        # The element to return is the one we've already peeked at.
        # Problem guarantees next() is called only on valid iterators.
        result = self.peeked_element
        
        # After returning, we need to advance our cache to the next element.
        if self.iterator.hasNext():
            self.peeked_element = self.iterator.next()
        else:
            # The underlying iterator is now exhausted.
            self.peeked_element = None
            
        return result

    def hasNext(self):
        """
        :rtype: bool
        """
        # The iterator has a next element if our cache is not empty.
        return self.peeked_element is not None

# 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].

Peeking Iterator in Java

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> iterator;
    private Integer peekedElement; // Caches the next element.

	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
        this.iterator = iterator;
        // Pre-fetch the first element to initialize the peekedElement.
        if (this.iterator.hasNext()) {
            peekedElement = this.iterator.next();
        } else {
            // If the original iterator is empty, there is no element to peek.
            peekedElement = null;
        }
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        // Simply return the cached element. No advancement of any pointer.
        return peekedElement;
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
        // Per problem constraints, next() is only called when hasNext() is true,
        // so peekedElement will not be null here.
        Integer result = peekedElement;

        // After 'consuming' the peekedElement, we must advance our cache
        // to the next element from the underlying iterator.
        if (iterator.hasNext()) {
            peekedElement = iterator.next();
        } else {
            // The underlying iterator is now exhausted.
            peekedElement = null;
        }
        
        return result;
	}
	
	@Override
	public boolean hasNext() {
        // If we have a cached element, it means there is a next element.
	    return peekedElement != null;
	}
}

Peeking Iterator in C++

/*
 * Below is the interface for Iterator, which is already defined for you.
 * **DO NOT** modify the interface for Iterator.
 *
 *  class Iterator {
 *		struct Data;
 * 		Data* data;
 *  public:
 *		Iterator(const vector<int>& nums);
 * 		Iterator(const Iterator& iter);
 *
 * 		// Returns the next element in the iteration.
 *		int next();
 *
 * 		// Returns true if the iteration has more elements.
 *		bool hasNext() const;
 *	};
 */

class PeekingIterator : public Iterator {
private:
    int peeked_element; // Caches the next element.
    bool has_peeked;    // A flag to indicate if we have a cached element.

public:
	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
	    // Initialize any member here.
	    // **DO NOT** save a copy of nums and manipulate it directly.
	    // You should only use the Iterator interface methods.

        // Try to pre-fetch the first element.
        // We use Iterator::hasNext() to call the base class's method.
        has_peeked = Iterator::hasNext();
        if (has_peeked) {
            // Cache the next element using the base class's next().
            peeked_element = Iterator::next();
        }
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	int peek() {
        // The problem guarantees that peek is called only when there is a next element.
        // So, has_peeked will be true, and peeked_element holds the value.
        return peeked_element;
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	int next() {
	    // The problem guarantees that next is called only when there is a next element.
        // We must return the current peeked element.
        int result = peeked_element;

        // After returning, we advance our cache to the next element from the base iterator.
        has_peeked = Iterator::hasNext();
        if (has_peeked) {
            peeked_element = Iterator::next();
        }
        
        return result;
	}
	
	bool hasNext() const {\n        // The presence of a next element is determined by our cache flag.
	    return has_peeked;
	}
};

Peeking Iterator in TypeScript

/**
 * // This is the Iterator's API interface.
 * // You should not implement it, or speculate about its implementation
 * class Iterator {
 *      hasNext(): boolean {}
 *
 *      next(): number {}
 * }
 */

class PeekingIterator {
    private iterator: Iterator;
    private peekedElement: number | null; // Caches the next element. null indicates end of iteration.

    constructor(iterator: Iterator) {
        this.iterator = iterator;
        // Pre-fetch the first element to initialize the peekedElement.
        if (this.iterator.hasNext()) {
            this.peekedElement = this.iterator.next();
        } else {
            // If the original iterator is empty, there's no element to peek.
            this.peekedElement = null;
        }
    }

    peek(): number {
        // Simply returns the cached element. Per problem constraints, peek() is only
        // called when hasNext() is true, so peekedElement cannot be null.
        return this.peekedElement!;
    }

    next(): number {
        // Per problem constraints, next() is only called when hasNext() is true,
        // so peekedElement will not be null.
        const result = this.peekedElement!;

        // After 'consuming' the peekedElement, we must advance our cache
        // to the next element from the underlying iterator.
        if (this.iterator.hasNext()) {
            this.peekedElement = this.iterator.next();
        } else {
            // The underlying iterator is now exhausted.
            this.peekedElement = null;
        }

        return result;
    }

    hasNext(): boolean {
        // If we have a cached element, it means there is a next element.
        return this.peekedElement !== null;
    }
}

/**
 * Your PeekingIterator object will be instantiated and called as such:
 * var obj = new PeekingIterator(iterator)
 * var param_1 = obj.peek()
 * var param_2 = obj.next()
 * var param_3 = obj.hasNext()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.