Unwrap Deeply Nested Lists Into One Sequence
Stacks & QueuesAuto-graded · 18 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a depth-first, left-to-right traversal where integers are leaves and lists are internal nodes. A recursive version is simple, but with up to 200,000 nodes the nesting can be 200,000 levels deep, which exceeds Python's default recursion limit. So we replace the call stack with an explicit one.
What a recursive call frame remembers is the position inside the parent list. A Python iterator is exactly that: a paused position within a list. We keep a stack of iterators:
- The top iterator belongs to the list currently being read.
- If it yields an integer, append it to the output.
- If it yields a list, push an iterator for that list and stop reading the parent for now. The parent's iterator stays on the stack, paused right after that child.
- When the top iterator is exhausted, pop it and the parent resumes.
The for ... else construct makes this compact: break happens when we descend, and the else branch (loop ended naturally) pops the finished list. Re-entering for x in stack[-1] continues from the paused position because calling iter() on an iterator returns itself.
Why it is correct
The stack always holds iterators for the chain of lists from the root to the list currently being read. Integers are emitted as they are read, and a list is fully consumed before its parent resumes, which is exactly depth-first, left-to-right order. Each list is pushed once and popped once, and each element is read once, so nothing is skipped or repeated. Empty lists are pushed and popped immediately without output. The input is only read through iterators, so it is never modified. Checking isinstance(x, list) instead of truthiness keeps 0 and negatives intact.
Complexity
With N the total number of integers plus lists and D the maximum depth:
- Time: O(N).
- Space: O(D) for the iterator stack, plus O(N) for the output. The stack lives on the heap, so deep nesting is safe.
Reference solution
def unwrap_nested(items: list) -> list[int]:
out = []
# Each iterator remembers the reading position inside one list on the current path.
stack = [iter(items)]
while stack:
for x in stack[-1]:
if isinstance(x, list):
# Descend; the parent's iterator keeps its place.
stack.append(iter(x))
break
out.append(x)
else:
# Current list fully consumed.
stack.pop()
return out