TRT
Sign in
mediumCoreLeetCode#explicit stack#lazy iteration

Flatten nested list iterator

Iterate over the integers of an arbitrarily nested list lazily, keeping your place with an explicit stack instead of recursion.

The Runtime Theory Team1 min read
Taught inRecursion vs iterationPro — members onlyAny recursion can become a loop and any loop a recursion. Tail calls turn into loops with an accumulator, and general recursion into a loop over an explicit stack. Choose by clarity, depth and cost.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

in[[1, 1], 2, [1, 1]]

out[1, 1, 2, 1, 1]

in[1, [4, [6]]]

out[1, 4, 6]

in[[], [3]]

out[3]

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

  1. Keep a stack of the items still to visit, pushing each list's items in reverse so the first is on top.
  2. In hasNext, pop lists off the top and push their contents until the top is an integer or the stack is empty.
  3. next then pops that integer.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save