Flatten and Filter a Nested Configuration Tree
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests the ability to write an iterator-style traversal over arbitrarily nested dicts and lists to extract leaf values matching a type filter.
Flatten and Filter a Nested Configuration Tree
Modern applications store configuration as deeply nested structures — a mix of dictionaries (keyed sections) and lists (ordered collections) that can be nested inside one another to arbitrary depth. You need to extract all leaf values from such a structure and return them in a specific order, optionally filtered by type.
Definitions
- A leaf value is any value that is not a
dictand not alist. - Traversal order follows depth-first, left-to-right rules:
- For a
dict, process keys in lexicographic (alphabetical) order. - For a
list, process elements in index order (0, 1, 2, …).
- For a
- The
type_filterargument is a string that may be:"any"— return all leaf values regardless of type."int"— return only leaves whereisinstance(value, int)andnot isinstance(value, bool)."float"— return only leaves whereisinstance(value, float)."str"— return only leaves whereisinstance(value, str)."bool"— return only leaves whereisinstance(value, bool)."none"— return only leaves that areNone.
Task
Implement:
def collect_leaves(config: dict, type_filter: str) -> list:
configis the root, which is always adict(possibly empty).- Returns a list of leaf values (in traversal order) that match
type_filter.
Notes
boolis a subclass ofintin Python, so you must distinguish them carefully:TrueandFalsematch"bool"but not"int".- Integer values like
0,1,42match"int"but not"bool".
floatvalues like3.14do not match"int", even though they might be whole numbers.- The root is always a
dict; nested structures may contain dicts or lists at any level. - An empty
dictor emptylistcontributes no leaves.
Constraints
configis always adictat the root level.- Nesting depth ≤ 20.
- Total number of nodes (dicts + lists + leaves) ≤ 2,000.
type_filteris always one of:"any","int","float","str","bool","none".- Leaf values are drawn from:
int(non-bool),float,str,bool,None. - Dict keys are always strings.
Examples
Example 1
Input: collect_leaves({'z': 1, 'a': [True, 'hello', 2], 'm': {'x': None, 'b': 3.14}}, 'int')
Output: [2, 1]
Example 2
Input: collect_leaves({'server': {'host': 'localhost', 'port': 8080, 'debug': True}, 'limits': [100, 200, 300]}, 'any')
Output: [100, 200, 300, True, 'localhost', 8080]
Example 3
Input: collect_leaves({'alpha': {'beta': {'gamma': False}}, 'delta': []}, 'bool')
Output: [False]
Hints
Hint 1
Use a recursive helper (or an explicit stack) that processes dicts by sorted keys and lists by index; any non-dict, non-list value is a leaf to consider.
Hint 2
Be careful with Python's type hierarchy: isinstance(True, int) is True, so you need an explicit bool check before the int check when filtering.
Hint 3
An iterative approach with a stack works well — push dict values in reverse-sorted-key order (or list elements in reverse index order) so that popping gives you the correct left-to-right traversal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is a depth-first traversal over a heterogeneous tree where internal nodes are either dict (children accessed by sorted keys) or list (children accessed by index), and leaves are any other Python value.
Algorithm
-
Define a
matches(value)predicate that checks the type filter. The trickiest part is thebool/intdistinction: sinceboolis a subclass ofintin Python,isinstance(True, int)returnsTrue. We must therefore checkboolfirst and explicitly exclude booleans from the"int"filter. -
Write a recursive
traverse(node)function:- If
nodeis adict, iterate over its keys in sorted order and recurse on each value. - If
nodeis alist, iterate in index order and recurse on each element. - Otherwise,
nodeis a leaf: if it matches the filter, append it to the result list.
- If
-
Call
traverse(config)and returnresult.
Correctness
- Sorted dict keys guarantee deterministic order regardless of insertion order.
- The
bool-before-intcheck inmatchescorrectly separates the two types. - Empty dicts and lists are handled naturally: neither branch appends anything.
Complexity
- Time: O(N log K) where N is the total number of nodes and K is the maximum number of keys in any single dict (the log K factor comes from sorting keys at each dict level).
- Space: O(D) for the recursion stack, where D is the maximum nesting depth. The output list is O(L) for L leaves.
from typing import Any
def collect_leaves(config: dict, type_filter: str) -> list:
def matches(value: Any) -> bool:
if type_filter == "any":
return True
if type_filter == "bool":
return isinstance(value, bool)
if type_filter == "int":
return isinstance(value, int) and not isinstance(value, bool)
if type_filter == "float":
return isinstance(value, float)
if type_filter == "str":
return isinstance(value, str)
if type_filter == "none":
return value is None
return False
result = []
def traverse(node: Any) -> None:
if isinstance(node, dict):
for key in sorted(node.keys()):
traverse(node[key])
elif isinstance(node, list):
for item in node:
traverse(item)
else:
if matches(node):
result.append(node)
traverse(config)
return result
Common Pitfalls
- Forgetting that
isinstance(True, int)isTruein Python — failing to guard against this gives wrong results for"int"and"bool"filters. - Iterating over dict keys without sorting — produces non-deterministic output.
- Treating
Noneas a non-leaf or recursing into it (it is a valid leaf value).