Flatten and rebuild nested Python containers
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in SpaceXAI's technical phone screen, last asked Mar 2026. It tests recursion and python.
Write two functions. flatten takes an arbitrarily nested mix of lists, tuples and dicts whose leaves are integers and returns the integers as one flat list, in traversal order. unflatten takes the original structure and a flat list of new values and builds a structure of exactly the same shape, with the same container types and dict keys, filled with the new values in the same order.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
flatten(obj) -> list[int]: depth-first, left to right. Lists and tuples are walked in index order, dicts in key insertion order (values only; keys are kept as structure). -
unflatten(structure, values: list[int]): returns a new object with the shape ofstructure, whosei-th leaf isvalues[i]. RaisesValueErroriflen(values)differs from the number of leaves. It never mutatesstructure.
Example
s = [1, (2, 3), {"a": 4, "b": [5, ()]}]
flatten(s) -> [1, 2, 3, 4, 5]
unflatten(s, [10, 20, 30, 40, 50]) -> [10, (20, 30), {"a": 40, "b": [50, ()]}]
unflatten(s, [10, 20]) -> ValueError # 5 leaves expected
The empty tuple holds no leaves, so it stays as ().
Constraints
- Containers are only
list,tupleanddict; every leaf is anint. - Nesting can be deep enough that recursion depth is worth discussing.
-
unflatten(s, flatten(s))must equals.
Clarifying questions
- Should dicts be walked in insertion order or in sorted key order?
- Can a dict key itself be a container, and should keys ever be flattened?
- What should happen on a leaf of another type (float, string,
None): error or treat as a leaf? - Should
unflattenreject too many or too few values, or ignore extras? - Can the same sub-object appear twice in the structure (shared references)?
What a strong answer covers
- One recursive walk shared by both directions, so the traversal order can never disagree;
unflattenconsumes the values with an iterator or index. - Container types preserved exactly (a tuple comes back as a tuple, dict key order kept).
- O(n) time in the total number of containers and leaves.
- Empty containers, a bare integer at the top level and wrong value counts handled.
- Tests including the round trip on random structures.
Follow-ups
- Make both functions iterative with an explicit stack for very deep nesting.
- Return a compact "spec" of the shape from
flattensounflattenneeds only the spec and the values (the way pytree libraries work). - Support custom container types through a registry of flatten and unflatten rules.
- Leaves are tensors and the flat list is fed to an optimizer: what changes?
Where it's asked
- SpaceXAI · Technical phone screen · Last asked Mar 202645 min · Live applied coding on a shared platform such as CoderPad · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
