Split a Nested Structure into Values and a Shape Template
Trees & GraphsAuto-graded · 22 test casesLast updated
Implement a single function that extracts leaves and a shape template from nested lists and dicts, then rebuilds the original from them, testing recursion and traversal order.
Values and Shape Template
You are given an arbitrarily nested structure built from Python lists and dictionaries. Anything that is not a list or a dict (integers, floats, strings, booleans, None, ...) is a leaf.
Write a single function that does three things and returns all three results:
- Collect the leaves. Produce a flat list
valuesof every leaf, in depth-first, left-to-right order. Lists are visited by index order. Dictionaries are visited in their key insertion order. - Build a shape template. Produce a
templatethat has the same shape as the input, but with each leaf replaced by the marker string"V". Lists keep their length, and dicts keep the same keys in the same order. Empty containers stay empty. - Rebuild the input. Using only
valuesandtemplate, reconstruct a structure equal to the original input by placing the k-th leaf value into the position of the k-th"V"marker in the template.
The function returns a list of exactly three items: [values, template, rebuilt].
Rules
- Only
listanddictcount as containers. Every other object is a leaf, including a string that happens to be"V". Such a string goes intovalueslike any other leaf, and its slot in the template is still"V". - If the input itself is a leaf, then
valuesis a one-element list holding it, the template is"V", andrebuiltis that same leaf. - An empty list or empty dict contributes no values and appears unchanged in the template.
- Dictionary keys are strings.
- The rebuilt structure must be equal to the input.
Constraints
- The input contains only lists, dicts with string keys, and leaf values (ints, floats, strings, booleans,
None). - The nesting depth is small enough for ordinary recursion to work.
- The returned value is a list of three elements in the order
values,template,rebuilt.
Examples
Example 1
Input: split_and_rebuild({'a': [1, 2], 'b': {'c': 3}})
Output: [[1, 2, 3], {'a': ['V', 'V'], 'b': {'c': 'V'}}, {'a': [1, 2], 'b': {'c': 3}}]
Example 2
Input: split_and_rebuild([1, {'x': [2, 3]}, 4])
Output: [[1, 2, 3, 4], ['V', {'x': ['V', 'V']}, 'V'], [1, {'x': [2, 3]}, 4]]
Example 3
Input: split_and_rebuild({'empty_list': [], 'empty_dict': {}, 'value': None})
Output: [[None], {'empty_list': [], 'empty_dict': {}, 'value': 'V'}, {'empty_list': [], 'empty_dict': {}, 'value': None}]
Example 4
Input: split_and_rebuild({'name': 'x', 'scores': [1.5, 2], 'active': True})
Output: [['x', 1.5, 2, True], {'name': 'V', 'scores': ['V', 'V'], 'active': 'V'}, {'name': 'x', 'scores': [1.5, 2], 'active': True}]
Hints
Hint 1
The template is the input with every leaf swapped for a marker. Build it with one recursive pass that appends each leaf to a shared list as it is encountered.
Hint 2
To rebuild, walk the template in the same order as before and keep a cursor into `values`. Each time you meet a marker, take the next value and advance the cursor.
Hint 3
Avoid `pop(0)` or slicing for consuming values, since these are O(n) each. Use an index counter or an iterator. Check for list and dict types before treating something as a leaf.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The template is the input with its leaves removed: containers keep their shape, and every leaf becomes "V".
Extracting values and template. Do one recursive pass:
- For a list, recurse on each element and return the list of child templates.
- For a dict, recurse on each value and return a dict with the same keys, in the same order.
- Otherwise the node is a leaf. Append it to the shared
valueslist and return"V".
Rebuilding. Walk the template in the same order, keeping a cursor into values:
- A list template node becomes a list of rebuilt children.
- A dict template node becomes a dict of rebuilt children.
- A
"V"marker consumesvalues[cursor]and advances the cursor.
In the reference solution the container checks come first, so the marker case is simply the fallthrough for a non-container. This also means a data value equal to "V" can never be confused with a marker.
Why it is correct
Both passes traverse in the same order: list index order and dict insertion order (guaranteed in Python 3.7+). The template has exactly the same shape as the input, so the rebuild pass meets the markers in exactly the order the leaves were appended. By induction on depth, each subtree is rebuilt from the contiguous slice of values that its own leaves produced.
Empty containers map to empty containers and consume no values. A top-level leaf gives values = [leaf], template "V", and a rebuild that returns the leaf.
Complexity
Let N be the total number of nodes and D the nesting depth.
- Time: O(N), since each node is visited once per pass and consuming a value is O(1) with an index cursor.
- Space: O(N) for
values,templateandrebuilt, plus O(D) recursion stack.
Reference solution
from typing import List
def split_and_rebuild(data: object) -> List:
values = []
def make_template(node):
if isinstance(node, list):
return [make_template(item) for item in node]
if isinstance(node, dict):
return {key: make_template(val) for key, val in node.items()}
values.append(node)
return "V"
template = make_template(data)
cursor = 0
def rebuild(tnode):
nonlocal cursor
if isinstance(tnode, list):
return [rebuild(child) for child in tnode]
if isinstance(tnode, dict):
return {key: rebuild(child) for key, child in tnode.items()}
item = values[cursor]
cursor += 1
return item
rebuilt = rebuild(template)
return [values, template, rebuilt]