1025. Peek-Ahead Iterator

Medium3.5 points estimatedDesignIteratorArray3 hints

A telemetry dashboard replays a recorded array of sensor readings one at a time, and the display layer often needs to glance at the upcoming reading before deciding whether to consume it. Build a class PeekIterator that is constructed from the array nums and walks it from left to right.

peek() returns the reading that the next call to next() would hand out, without moving forward. next() returns that reading and advances past it. hasNext() reports whether any readings remain. Every operation must run in O(1) time and the class may keep only a reference to nums plus a constant amount of extra state.

Example 1

Input:
operations = ["PeekIterator","peek","next","peek","hasNext","next","next","hasNext"]arguments = [[[4,8,15]],[],[],[],[],[],[],[]]
Output:
[null,4,4,8,true,8,15,false]
Explanation:

Peeking twice never moves the cursor; after the three readings 4, 8 and 15 have been consumed, hasNext turns false.

Example 2

Input:
operations = ["PeekIterator","hasNext","peek","peek","next","hasNext"]arguments = [[[-3]],[],[],[],[],[]]
Output:
[null,true,-3,-3,-3,false]
Explanation:

A single reading can be peeked at any number of times and only disappears after next.

Example 3

Input:
operations = ["PeekIterator","next","next","peek","next","peek","hasNext","next","hasNext"]arguments = [[[10,20,30,40]],[],[],[],[],[],[],[],[]]
Output:
[null,10,20,30,30,40,true,40,false]
Explanation:

Each peek shows the value that the very next call to next returns, here 30 and then 40.

Constraints

0 ≤ nums.length ≤ 1000

-109 ≤ nums[i] ≤ 109

At most 3000 calls in total; peek and next are only called while hasNext() would return true.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(1) per operation
Space
O(1) extra

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.