Medium

Quiz

#341 Flatten Nested List Iterator

APPROACH

You are given a nested list of integers nestedList where each element is either an integer or a further-nested list. Construct a flattening iterator that yields integers in the natural left-to-right traversal order.

Implement the NestedIterator class:

- NestedIterator(List<NestedInteger> nestedList) Sets up the iterator over nestedList.

- int next() Advances past and returns the next integer.

- boolean hasNext() Returns true when at least one integer remains.

Validation pseudocode:

initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res

Your iterator passes if res matches the fully flattened list.

Example 1:

initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res

Example 2:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 3:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
1 of 4
1:00

What is the optimal approach for this problem?