Prune a Labeled Tree by Forbidden Substring
Trees & GraphsAuto-graded · 24 test casesLast updated
Recursively copy an n-ary tree while dropping every node whose label contains a given substring, together with its subtree, without mutating the input.
Prune a Labeled Tree
You are given a rooted tree where each node can have any number of children. A node is a dictionary with two keys:
"value": a string label."children": a list of child nodes, in order. A node with no children has an empty list. If the"children"key is missing, treat it as an empty list.
Write a function that takes the root of such a tree and a string pattern, and returns a new tree in which every node whose "value" contains pattern as a substring has been removed together with all of its descendants.
Rules
- Matching is case-sensitive and checks whether
patternoccurs anywhere inside the node's"value". - A removed node's descendants are removed too, even if their own labels do not contain
pattern. - The relative order of the surviving children must be preserved.
- If the root matches, return
None. - If
patternis the empty string, nothing is removed: return a full copy of the tree. - The input tree must not be modified. The returned tree must be built from new dictionaries and lists.
- Every node in the returned tree has both the
"value"and"children"keys, with"children"always being a list.
Constraints
- The tree has at least one node.
- Node values are strings, possibly empty.
patternis a string, possibly empty.- The tree is small enough that a recursive traversal fits in the default Python recursion limit.
- Return type: a dictionary representing the pruned tree, or
Noneif the root is removed.
Examples
Example 1
Input: prune_tree_by_substring({'value': 'root', 'children': [{'value': 'sensors', 'children': [{'value': 'lidar-front', 'children': []}, {'value': 'camera-debug', 'children': [{'value': 'frames', 'children': []}]}]}, {'value': 'debug-tools', 'children': [{'value': 'logger', 'children': []}]}, {'value': 'planner', 'children': []}]}, 'debug')
Output: {'value': 'root', 'children': [{'value': 'sensors', 'children': [{'value': 'lidar-front', 'children': []}]}, {'value': 'planner', 'children': []}]}
Example 2
Input: prune_tree_by_substring({'value': 'root', 'children': [{'value': 'alpha', 'children': []}, {'value': 'beta', 'children': [{'value': 'alphabet', 'children': []}]}]}, 'ha')
Output: {'value': 'root', 'children': [{'value': 'beta', 'children': []}]}
Example 3
Input: prune_tree_by_substring({'value': 'root', 'children': [{'value': 'child', 'children': []}]}, '')
Output: {'value': 'root', 'children': [{'value': 'child', 'children': []}]}
Hints
Hint 1
Think of the function as: given a node, either return None (the node is dropped) or return a fresh node whose children are the non-None results of recursing on the original children.
Hint 2
Once a node matches, you do not need to look at its children at all, since the whole subtree goes away with it.
Hint 3
In Python, the empty string is a substring of every string, so an empty pattern would drop everything if you do not handle it explicitly. Decide what the rules say it should do, and copy the tree in that case.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a depth-first traversal that builds the result as it goes.
For each node:
- If its
"value"containspattern, returnNone. The node and everything below it are dropped, and we never visit its children. - Otherwise, recurse into each child in order, keep only the non-
Noneresults, and return a new node with the same value and that list of surviving children.
Two special cases come from the rules:
- If the root matches, the recursion returns
Nonedirectly, which is the required answer. - An empty
patternis a substring of every string, so the normal check would delete everything. The rules say it should remove nothing, so we handle it up front by returning a plain deep copy.
Because every returned node is a freshly created dictionary with a freshly created list, the input is never modified.
Why it is correct
A node appears in the output exactly when neither it nor any of its ancestors matches. The recursion enforces this: a matching node returns None and its subtree is never explored, and a non-matching node is kept only if its parent was kept (since it is only reached through the parent's recursion). Children are processed in their original order, so order is preserved.
Complexity
- Time: O(sum of node-value lengths), since each node is visited at most once and each substring check costs at most linear in the label length (up to a factor depending on the pattern length for the search).
- Space: O(n) for the output tree plus O(h) recursion stack, where h is the tree height.
Reference solution
from typing import Dict, Optional
def prune_tree_by_substring(root: Dict[str, object], pattern: str) -> Optional[Dict[str, object]]:
def copy(node):
return {
"value": node["value"],
"children": [copy(c) for c in node.get("children", [])],
}
def prune(node):
if pattern in node["value"]:
return None
kept = []
for child in node.get("children", []):
result = prune(child)
if result is not None:
kept.append(result)
return {"value": node["value"], "children": kept}
if pattern == "":
return copy(root)
return prune(root)