KatInterview

Unwrap Deeply Nested Lists Into One Sequence

Stacks & QueuesAuto-graded · 18 test cases
MediumAuto-gradedStacks & Queuesstackdfsiterators

Last updated

Collect every integer from a structure of arbitrarily deep nested lists in left-to-right order, without recursion, so extremely deep inputs do not overflow the call stack.

Unwrap Deeply Nested Lists Into One Sequence

You are given a structure built from Python lists. Each element of a list is either an integer or another list, and lists may be nested to any depth.

Produce a single flat list holding every integer in the structure, in the order you would meet them when reading the structure from left to right, descending into each inner list as soon as you reach it.

Rules

  • Every integer appears in the output exactly once, in depth-first, left-to-right order.
  • Empty lists (at any depth) contribute nothing to the output.
  • Zero and negative numbers are ordinary integers and must be kept.
  • The input must not be modified.
  • If the input list contains no integers at all, return an empty list.

Constraints

  • The structure contains only Python integers and Python lists.
  • The total count of integers plus list nodes is at most 200_000.
  • Nesting can be deep enough that the default recursion limit of Python is a concern, so plan for inputs such as a chain of many nested lists.
  • Do not mutate the input.

Examples

Example 1

Input: unwrap_nested([1, [2, [3, 4], []], 5])

Output: [1, 2, 3, 4, 5]

Example 2

Input: unwrap_nested([[[]], -1, [0]])

Output: [-1, 0]

Hints

Hint 1

When you step into an inner list, what information about the outer list must you remember so you can continue afterward?

Hint 2

Recursion keeps that information in call frames. You can keep it yourself in an explicit stack instead, so the depth is not limited by the interpreter.

Hint 3

Store an iterator for each list currently being read. Resume the top iterator; if it yields a list, push that list's iterator; if it is exhausted, pop it. Check the type of each element rather than its truthiness so that 0 is handled correctly.