Talentd
FleetCode

284. Peeking Iterator

Medium61.9% acceptance3 companies

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.
  • int next() Returns the next element in the array and moves the pointer to the next element.
  • boolean hasNext() Returns true if there are still elements in the array.
  • int peek() Returns the next element in the array without moving the pointer.

Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

Example 1:

Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next();    // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek();    // return 2, the pointer does not move [1,2,3].
peekingIterator.next();    // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • All the calls to next and peek are valid.
  • At most 1000 calls will be made to next, hasNext, and peek.
Follow up: How would you extend your design to be generic and work with all types, not just integer?

Asked at 3 companies

Hints open one at a time

Hint 1
Think of "looking ahead". You want to cache the next element.
Hint 2
Is one variable sufficient? Why or why not?
Hint 3
Test your design with call order of peek() before next() vs next() before peek().
Hint 4
For a clean implementation, check out Google's guava library source code.
4:05
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Below is the interface for Iterator, which is already defined for you.
2#
3# class Iterator:
4# def __init__(self, nums):
5# """
6# Initializes an iterator object to the beginning of a list.
7# :type nums: List[int]
8# """
9#
10# def hasNext(self):
11# """
12# Returns true if the iteration has more elements.
13# :rtype: bool
14# """
15#
16# def next(self):
17# """
18# Returns the next element in the iteration.
19# :rtype: int
20# """
21
22class PeekingIterator:
23 def __init__(self, iterator):
24 """
25 Initialize your data structure here.
26 :type iterator: Iterator
27 """
28
29
30 def peek(self):
31 """
32 Returns the next element in the iteration without advancing the iterator.
33 :rtype: int
34 """
35
36
37 def next(self):
38 """
39 :rtype: int
40 """
41
42
43 def hasNext(self):
44 """
45 :rtype: bool
46 """
47
48
49# Your PeekingIterator object will be instantiated and called as such:
50# iter = PeekingIterator(Iterator(nums))
51# while iter.hasNext():
52# val = iter.peek() # Get the next element but not advance the iterator.
53# iter.next() # Should return the same value as [val].
Starter codePython 3Spaces: 4
Examples
Input
["PeekingIterator","next","peek","next","next","hasNext"]
[[[1,2,3]],[],[],[],[],[]]
Your code is saved on this device.Solution