Flatten Nested List Iterator
Problem
You are given a nested list where each element is either an integer or another nested list, to arbitrary depth. Elements are exposed only through a NestedInteger interface:
isInteger():Trueif this element holds a single integer.getInteger(): the integer, ifisInteger()is true.getList(): the list of childNestedIntegerelements, ifisInteger()is false.
Implement NestedIterator with __init__(nestedList), next() returning the next integer in left-to-right depth-first order, and hasNext() returning whether any integers remain. Callers may invoke hasNext() any number of times (including zero) between calls to next(), and will only call next() when an integer remains.
- The top-level list holds at most a few hundred elements.
- Integer values fit in a signed 32-bit range.
- Nested lists may be empty at any depth.
Examples
[[5,5],9,[5,5]]→next()repeatedly yields5, 5, 9, 5, 5.[2,[7,[8]]]→ yields2, 7, 8.[[], [[]], 3, []]→ yields only3;hasNext()must skip over the empty lists rather than reporting there is a next element.
Hints
- Recursively flattening everything into an array in the constructor works, but what if the structure is enormous or the caller only reads the first few elements?
- Depth-first traversal that can pause: replace recursion with an explicit stack.
- Push the top-level elements onto a stack in reverse order. In
hasNext, while the top is a list, pop it and push its children in reverse; stop when the top is an integer or the stack is empty.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.