Peeking Iterator — LeetCode 284 Python Solution
MediumDesignArrayIterator
- Problem
- #284
- Reading time
- 11 min
- Source
- leetcode.com
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
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.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
| Measure | Complexity |
|---|---|
| Time | Varies by operation |
| Space | Varies by operation auxiliary |
Related problems
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.