Implement an iterator with next() and hasNext() over the integers in a nested list, in order, where each element is either an integer or another nested list.
Before you code
Flattening everything up front with recursion is easy, but it does all the work at once and recurses as deep as the nesting. An iterator should do only the work needed for the next value, and it can't pause in the middle of a recursive call, so it needs its own stack.
Hints
- Keep a stack of the items still to visit, pushing each list's items in reverse so the first is on top.
- In
hasNext, pop lists off the top and push their contents until the top is an integer or the stack is empty. nextthen pops that integer.- Watch for empty lists, such as
[[]], which contain no integers at all.
Production & complexity notes
When solving Flatten nested list iterator on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Recursion vs iteration to reinforce the underlying pattern.
What it practices
Keeping pending work on an explicit stack, from Recursion vs iteration.