Peeking Iterator

Medium · Design · Array · Design · Iterator

Problem

An iterator hands out a sequence one element at a time: next() returns the next element and moves past it, and hasNext() says whether any are left. Design a PeekingIterator that adds one more operation, peek(), which returns the next element without moving past it.

Implement the class:

Every call to peek() and next() is made while an element is left. Calls are given as two lists: the operation names, and each call's arguments.

Examples

Input: operations = ["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
arguments = [[[1, 2, 3]], [], [], [], [], []]
Output: [null, 1, 2, 2, 3, false]

peek() sees 2 and the following next() still returns 2.

Input: operations = ["PeekingIterator", "peek", "peek", "next", "hasNext"]
arguments = [[[7]], [], [], [], []]
Output: [null, 7, 7, 7, false]

Peeking twice returns the same element and consumes nothing.

Constraints

Approaches

Follow-up

To work with any element type, the cache needs a separate "has a value" flag rather than a sentinel such as None, because None may itself be an element. The same one-element lookahead is how tokenizers let a parser peek at the next token.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…