Flatten and Iterate a Nested Registry
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests the ability to implement a depth-first iterator over arbitrarily nested lists and dicts that yields leaf values in traversal order.
Flatten a Nested Registry
A configuration registry stores values in a deeply nested structure built from two container types:
- Lists – ordered sequences; iterate elements left to right.
- Dicts – string-keyed mappings; iterate keys in sorted (lexicographic) order.
A leaf is any value that is neither a list nor a dict (it may be an int, float, str, bool, or None).
Write a function that accepts such a nested structure (which is itself either a list, dict, or a leaf) and returns a flat list of all leaf values encountered in a depth-first traversal.
Traversal rules
- If the current node is a list, visit each element in index order (0, 1, 2, …).
- If the current node is a dict, visit each value in ascending sorted order of its keys.
- If the current node is a leaf, emit it.
Constraints
- The structure may be nested up to 50 levels deep.
- A single structure may contain up to 2 000 leaf values.
- Dict keys are non-empty strings.
- Leaf values may be any JSON-compatible scalar:
int,float,str,bool, orNone. - An empty list
[]or empty dict{}contributes zero leaves. - The top-level input is guaranteed to be a list, dict, or scalar leaf.
Examples
Example 1
Input: flatten_registry({'b': 2, 'a': 1})
Output: [1, 2]
Example 2
Input: flatten_registry([1, [2, 3], [4, [5]]])
Output: [1, 2, 3, 4, 5]
Example 3
Input: flatten_registry({'z': [10, {'m': 20, 'a': 30}], 'a': 99})
Output: [99, 10, 30, 20]
Hints
Hint 1
Think recursively: handle lists, dicts, and leaves as three separate cases in one function.
Hint 2
For dicts, remember to sort the keys before recursing into their values — the order matters for correctness.
Hint 3
You can use an isinstance check to distinguish containers from leaves; bool is a subclass of int in Python, but since you emit it as-is you don't need to special-case it.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem reduces to a standard depth-first traversal over a heterogeneous tree where internal nodes are either lists or dicts and leaves are scalar values.
Algorithm:
- Define a recursive helper
_dfs(current)that appends to an accumulator list. - If
currentis alist, recurse on each element in order. - If
currentis adict, sort the keys lexicographically, then recurse on each corresponding value in that order. - Otherwise,
currentis a leaf — append it directly.
Why it is correct:
Every node is visited exactly once. The sorted-key rule for dicts gives a deterministic, well-defined ordering regardless of Python's internal dict ordering. Lists preserve insertion order naturally.
Edge cases handled:
- Empty lists and empty dicts produce no leaves (the loops simply don't execute).
- A bare scalar at the top level is emitted immediately as a single-element result.
boolandNoneare leaves in Python's type hierarchy (neither alistnor adict), so they are emitted correctly without special-casing.boolis a subclass ofintin Python, but since we never check forintspecifically, this causes no issue.
Complexity:
- Time: O(N log K) where N is the total number of nodes (containers + leaves) and K is the maximum number of keys in any single dict (for the sort step). In practice this is effectively O(N).
- Space: O(N) for the output list plus O(D) call-stack depth where D ≤ 50.
from typing import Any
def flatten_registry(node: Any) -> list:
result = []
def _dfs(current):
if isinstance(current, list):
for item in current:
_dfs(item)
elif isinstance(current, dict):
for key in sorted(current.keys()):
_dfs(current[key])
else:
# Leaf: int, float, str, bool, None
result.append(current)
_dfs(node)
return result