MediumNo. 0284

Peeking Iterator — LeetCode 284 Python Solution

Topics
Design, Array, Iterator
Reading time
11 min

The problem

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.

Example

Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
Output
[null, 1, 2, 2, 3, false]
Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]

Python solution

PythonSolution
# 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.has_peeked = False
        self.peeked_element = None

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if not self.has_peeked:
            self.peeked_element = self.iterator.next()
            self.has_peeked = True
        return self.peeked_element

    def next(self):
        """
        :rtype: int
        """
        if not self.has_peeked:
            return self.iterator.next()
        result = self.peeked_element
        self.has_peeked = False
        self.peeked_element = None
        return result

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

Complexity

Time
Varies by operation
Space · auxiliary
Varies by operation

Related problems

Related problems
No.ProblemDifficulty
0307Range Sum Query - MutableMedium
0295Find Median from Data StreamHard
0715Range ModuleHard
2276Count Integers in IntervalsHard
0900RLE IteratorMedium
0173Binary Search Tree IteratorMedium

Frequently asked questions

How hard is LeetCode 284. Peeking Iterator?

LeetCode 284. Peeking Iterator is rated Medium on LeetCode.

What is the time complexity of LeetCode 284. Peeking Iterator?

The Python solution on this page runs in Varies by operation.

What is the space complexity of LeetCode 284. Peeking Iterator?

The Python solution on this page uses Varies by operation auxiliary space.

What topics does LeetCode 284. Peeking Iterator cover?

LeetCode 284. Peeking Iterator is tagged Design, Array and Iterator on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.