← Questions

Flatten a nested list iterator

0
AirbnbCodingLast asked Apr 2026

A coding interview question asked in Airbnb's coding round, last asked Apr 2026. It tests iterators, stacks and recursion.

A nested list holds integers and other nested lists, to any depth. Produce its integers in left-to-right, depth-first order. First return them all as one flat list. Then provide them lazily, one at a time, through an iterator.

Part 1: flatten

Unless you agree on a different interface with the interviewer, assume:

  • flatten_nested(values: list) -> list[int]: all integers in order; empty lists contribute nothing. Don't modify the input.

Part 2: iterator

  • NestedIterator(values) with next() -> int and has_next() -> bool. Don't flatten up front: keep only a stack of positions.

Example

flatten_nested([1, [2, [3, 4], []], 5])      ->  [1, 2, 3, 4, 5]
flatten_nested([[], [7, [8, []]], 9, [[10]]]) ->  [7, 8, 9, 10]
flatten_nested([[[]]])                       ->  []

it = NestedIterator([[], [7, [8, []]], 9])
it.has_next() -> True, it.next() -> 7, it.next() -> 8, it.next() -> 9, it.has_next() -> False

Constraints

  • Only integers and lists; up to 2 * 10^5 integers and lists in total.
  • Nesting can be deeper than the recursion limit.

Clarifying questions

  • Can lists be empty, or contain only empty lists?
  • How deep can nesting go?
  • In the iterator, can next() be called without has_next() first?

What a strong answer covers

  • The recursive version, then an explicit stack so very deep nesting doesn't overflow.
  • For the iterator: a stack of (list, index) pairs; has_next() advances past empty lists until an integer is on top, so next() is O(1) amortized.
  • Why has_next() must do the skipping (a trailing empty list otherwise makes it lie).
  • O(n) total time; memory O(depth) for the iterator.
  • Tests: empty lists at every level, deep nesting, a single integer.

Follow-ups

  • Add remove() or peek().
  • Iterate in reverse.
  • Compute the sum of each integer times its depth.

Where it's asked

  • Airbnb · Coding · Last asked Apr 202645 min · Live coding, one or two rounds, from the same pool as the screen

What it tests

iterators · stacks · recursion

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding