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:
Example 2:
Example 3:
What is the optimal approach for this problem?