call(back)
Algorithms & Data StructuresmediumSign in to star problems

Lazy Nested-List Iterator

Flatten a nested list behind an iterator interface — hasNext() and next() — lazily: do not flatten everything in the constructor. Elements are integers or lists, nested arbitrarily deep.

it = NestedIterator([[1, 1], 2, [1, 1]])
// next() until hasNext() is false  ->  1, 1, 2, 1, 1

it = NestedIterator([[], [[]], [[], [3]]])
it.hasNext()  ->  true      // must skip arbitrarily deep empty nesting
it.next()     ->  3
it.hasNext()  ->  false

Calling hasNext() repeatedly must not consume anything.

Hints

Hint 1

Keep a stack of iterators, one per list you are inside; memory is O(depth). Advancing means: take the next item from the top iterator, pop when it is exhausted, push when the item is itself a list, stop when it is an integer.

Hint 2

Hold a one-element lookahead buffer so hasNext() can answer truthfully after skipping empty lists — and so peek() is later a one-liner.

Asked at