Problem 79 · Object & System Design
Flatten Nested List Iterator
01Problem
Given an arbitrarily nested list of integers, implement an iterator with next() and has_next() that yields the integers in order, lazily.
02Key insight
Keep a stack of iterators instead of flattening up front: has_next advances until the top yields an integer (pushing sub-iterators for lists, popping exhausted ones). Memory is O(depth), and empty sublists are handled naturally.
03Solution
Try it first.
TimeO(1) amortized per element
SpaceO(depth)
tests.py · 4 passing
tests.pypython5 lines
assert list(NestedIterator([[1, 1], 2, [1, 1]])) == [1, 1, 2, 1, 1]
assert list(NestedIterator([1, [4, [6]]])) == [1, 4, 6]
assert list(NestedIterator([[], [[]], [[], [7]], []])) == [7]
it = NestedIterator([])
assert not it.has_next()04Staff-level follow-up
Same pattern as streaming a JSON/Parquet nested column or walking a B-tree: a stack of cursors keeps memory at O(depth) so it works on inputs larger than RAM.