Skip to content
Onsite

Flatten Nested List Iterator

MediumP3Coding

You are given a nested list: an array whose items are each either an integer or another nested list (to any depth), for example [1, [2, [3]], 4].

Implement the NestedIterator class that walks the integers in left-to-right order:

  • NestedIterator(nestedList) initializes the iterator.
  • next() returns the next integer. It is only called when hasNext() would return true.
  • hasNext() returns true if integers remain.

Empty lists at any depth contribute nothing, so hasNext() must skip them. Do not flatten the whole list into a new array in the constructor; produce the values lazily.

Example 1

Input
["NestedIterator","next","next","next","hasNext","next","next","hasNext"] [[[[1,1],2,[1,1]]],[],[],[],[],[],[],[]]
Output
[null,1,1,2,true,1,1,false]
Why
Calling next three times returns 1, 2, 3, then hasNext is false.

Constraints

  • Total number of integers and lists <= 10^5
  • -10^9 <= integer <= 10^9
  • Nesting depth <= 1000.

Hints

Run checks the 2 visible tests, Submit all 8.