#284

Peeking Iterator

Medium
ArrayDesignIteratorIteratorCachingState Management
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach involves caching the next element when peek() is called, allowing us to return it without moving the iterator. This way, we only call next() when necessary.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a class PeekingIterator that takes an existing iterator as input.
  2. 2Step 2: Initialize a variable to store the next element and a boolean to track if it has been cached.
  3. 3Step 3: In the peek() method, check if the next element is cached; if not, call next() to cache it.
solution.py20 lines
1class PeekingIterator:
2    def __init__(self, iterator):
3        self.iterator = iterator
4        self.cache = None
5        self.has_cache = False
6
7    def next(self):
8        if self.has_cache:
9            self.has_cache = False
10            return self.cache
11        return self.iterator.next()
12
13    def hasNext(self):
14        return self.has_cache or self.iterator.hasNext()
15
16    def peek(self):
17        if not self.has_cache:
18            self.cache = self.iterator.next()
19            self.has_cache = True
20        return self.cache

Complexity note: The time complexity is O(n) since each element is processed at most once, and the space complexity is O(1) as we only store one cached element.

  • 1Caching the next element allows peek without moving the iterator.
  • 2Using a boolean flag helps track whether the next element is cached.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.