Python 0284.py
class PeekingIterator:
def __init__(self, iterator):
self.i = iterator
self.cache = None
def peek(self):
if self.cache is None:
self.cache = self.i.next()
return self.cache
def next(self):
if self.cache is None:
return self.i.next()
result = self.cache
self.cache = None
return result
def hasNext(self):
if self.cache is not None:
return True
else:
return self.i.hasNext()
Difficulty
and has an acceptance rate of about 62% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Iterator
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided PeekingIterator class wraps a standard iterator and adds the ability to look at the next element without advancing the underlying iterator. It maintains a single-element cache that stores a prefetched value when peek is called. All public methods (peek, next, hasNext) coordinate with this cache to ensure correct behavior while minimizing unnecessary calls to the wrapped iterator.
Initialization
def __init__(self, iterator):
self.i = iterator
self.cache = None
During construction the iterator to be wrapped is stored in self.i. The cache is initialized to None, indicating that no element has been prefetched yet. This simple state setup prepares the object for lazy fetching of the next value only when required.
Peek Operation
def peek(self):
if self.cache is None:
self.cache = self.i.next()
return self.cache
peek first checks whether the cache already holds a value. If the cache is empty, it retrieves the next element from the underlying iterator via self.i.next() and stores it. The method then returns the cached value. By caching the result, peek guarantees that subsequent calls to next will return the same element without advancing the iterator a second time.
Edge Cases Handled
When the iterator is exhausted, the underlying next call would raise an exception (as per typical iterator contracts). Because peek only invokes next when the cache is empty, it correctly propagates that exception at the moment the first attempt is made to look beyond the end of the sequence. The cache remains None in that situation, preserving the exhausted state for later calls.
Next Operation
def next(self):
if self.cache is None:
return self.i.next()
result = self.cache
self.cache = None
return result
next distinguishes two scenarios. If the cache is empty, it directly forwards the call to the wrapped iterator, returning the freshly fetched element. If the cache contains a prefetched value (set by a prior peek), it returns that value and clears the cache, thereby advancing the logical position of the iterator exactly once.
Edge Cases Handled
The method correctly handles the situation where a peek has been performed just before next. By returning the cached value and resetting the cache, it ensures that the element is not skipped or duplicated. If the iterator is exhausted and the cache is empty, the underlying iterator’s next will raise the appropriate exception, which next propagates unchanged.
HasNext Operation
def hasNext(self):
if self.cache is not None:
return True
else:
return self.i.hasNext()
hasNext first inspects the cache. If a prefetched element exists, the method can immediately report that another element is available without consulting the underlying iterator. Otherwise, it delegates to the wrapped iterator’s hasNext method.
Edge Cases Handled
When a value has been cached by peek, hasNext returns True even if the underlying iterator would report False because it has no further elements beyond the cached one. This correctly reflects the logical state of the PeekingIterator, where the cached element still constitutes a pending item.
Performance Optimizations
The central optimization is the single-element cache that eliminates redundant calls to the underlying iterator. A naïve implementation of peek might call next on the wrapped iterator each time, consuming an element and requiring a separate mechanism to “push back” the value. By storing the prefetched element, the class avoids this push-back step entirely, resulting in constant-time peek after the first fetch.
Additionally, hasNext benefits from the cache by providing an immediate answer when a prefetched element is present, bypassing any potentially expensive state checks inside the wrapped iterator. This lazy caching strategy ensures that the iterator advances only when the client explicitly requests the next element via next or when peek forces a single lookahead.
Overall, the design balances simplicity with efficient use of the underlying iterator’s interface, delivering predictable behavior with minimal overhead.
ELI5 - Simplified Explanation
Imagine there is a big magical bag filled with numbered cards. An iterator is like a robot that helps you pull the cards out one at a time. This code creates a special robot that has a tiny shelf called a cache right on its hand.
When asking the robot to peek, it looks at the next card in the bag without taking it out yet. If the robot has already seen a card and put it on its shelf, it shows you that card instead of reaching back into the bag.
When asking the robot for the next card, it checks if there is already one sitting on its shelf. If there is, it hands that card to you and clears off the shelf. If the shelf is empty, it reaches into the bag to get a new card for you.
When checking if there are more cards, the robot looks at its shelf first. If a card is sitting there, the robot knows there is definitely something to show. If the shelf is empty, the robot asks the bag if there are any cards left inside. This way, the robot always knows if the game can keep going.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lennylxx | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | TS | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lennylxx | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | TypeScript | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 281: Zigzag Iterator
Solved On The Same Day
- problem 401: Binary Watch
- problem 227: Basic Calculator II
- problem 241: Different Ways to Add Parentheses
- problem 299: Bulls and Cows
- problem 365: Water and Jug Problem
- problem 375: Guess Number Higher or Lower II
- problem 376: Wiggle Subsequence
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality