341 Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1: Given the list[[1,1],2,[1,1]],

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

Example 2: Given the list[1,[4,[6]]],

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

The Idea: A nestedList is nothing but a tree. Naturally, a tree is recursively traversed, but we don't have that luxiery here because call stack has to be saved, in a sense. Any nestedList can be represented as a cons cell (lisp idea). For example, the tree below represents the following list: (1 (2 6 7 8) 3 (4 (9 12)) (5 10 11)). As we can see, following a preorder traversal through this tree will reveal the correct order of the elements within the nested list. A preorder traversal can be accomplished iteratively using a stack.

The approach to this problem is the same, except that we'll need to store an iterator for every sublist.

Any element within a nestedList can be either of two things: an integer or a list. If the element is an integer, we're ok to output it. Otherwise, if it is a list, we need to push this list onto the stack, and initialize it's own iterator (starting from 0).

Complexity: O(N) time where N is the total number of element in the list (including the nested lists), and O(|deepest nestest list|) space

Last updated

Was this helpful?