Combine Config Trees and Parse a Canonical Encoding
Trees & GraphsAuto-graded · 18 test casesLast updated
Merge two keyed n-ary trees by summing values, encode them canonically, and strictly parse an encoded string with validation.
Combining Configuration Trees
A configuration is a rooted tree. Every node has:
key: a non-empty string that is unique among its siblings,val: an integer,children: a list of child nodes.
In this problem a tree is given as a nested dictionary, {"key": ..., "val": ..., "children": [...]}. The "children" entry may be missing, which means the node has no children. A whole tree may also be None, meaning empty.
Write one function that takes two trees first and second and an encoded string encoded. It does three things:
- Merge
firstandsecondinto a new tree. Neither input may be modified. - Decode
encodedinto a tree. - Encode both resulting trees in the canonical text format and return the two strings as a list.
Merge rules
- If both trees are
None, the result isNone. - If exactly one tree is
None, the result is a full copy of the other. - If both are non-empty, their root keys must be equal. Otherwise raise
ValueError. - Two nodes with equal keys merge into one node whose
valis the sum of the two values. - Their children are combined by key. A key present on both sides is merged recursively using these same rules. A key present on one side only is copied with its whole subtree.
Canonical text format
Noneis written as#.- A node is written as
key:val[child1,child2,...], where the children are written recursively and ordered by key in ascending (plain string) order. A node with no children is writtenkey:val[]. - This ordering applies to every tree you encode, including the decoded one, no matter what order its children had in the input.
- Integers are written in the usual decimal form, with no leading zeros and no plus sign.
Decoding rules
encoded is either exactly # (the empty tree) or a single node in the format above. The grammar is:
node := key ':' int '[' children? ']'
children := node (',' node)*
key := one or more characters, none of which is one of : [ ] ,
int := '-'? followed by one or more ASCII digits 0-9
Raise ValueError if encoded does not match this grammar exactly. Cases that must be rejected include:
- an empty string, or an empty key,
- a missing or invalid integer (a bare
-, a+sign, non-ASCII digits), - a missing
[or a missing or mismatched], - a stray comma, such as
a:1[b:2[],]ora:1[,b:2[]], - two children of the same node with the same key,
- any characters left over after the root node is fully parsed.
Leading zeros in an integer are accepted and read as the numeric value, so a:007[] decodes to value 7. Zero and negative values are accepted.
Output
Return a list of two strings: [canonical(merged_tree), canonical(decoded_tree)].
If the merge fails because the root keys differ, or the decoding fails because the string is malformed, the ValueError must propagate to the caller.
Constraints
- Each tree has between
0and10^4nodes. - Keys have length
1to32and are alphanumeric in the input trees. Sibling keys in the input trees are unique. - Values satisfy
-10^6 <= val <= 10^6in the input trees. - Tree depth is at most
1000.
Examples
Example 1
Input: combine_config_trees({'key': 'root', 'val': 5, 'children': [{'key': 'a', 'val': 2, 'children': []}, {'key': 'b', 'val': 3, 'children': []}]}, {'key': 'root', 'val': 10, 'children': [{'key': 'b', 'val': 4, 'children': []}, {'key': 'c', 'val': 1, 'children': []}]}, 'root:15[a:2[],b:7[],c:1[]]')
Output: ['root:15[a:2[],b:7[],c:1[]]', 'root:15[a:2[],b:7[],c:1[]]']
Example 2
Input: combine_config_trees({'key': 'A', 'val': 1, 'children': []}, None, '#')
Output: ['A:1[]', '#']
Example 3
Input: combine_config_trees(None, {'key': 'root', 'val': -2, 'children': [{'key': 'z', 'val': 0, 'children': []}, {'key': 'a', 'val': 5, 'children': []}]}, 'root:0[a:5[],z:0[]]')
Output: ['root:-2[a:5[],z:0[]]', 'root:0[a:5[],z:0[]]']
Hints
Hint 1
Write a helper that merges two optional nodes. If one is missing, it simply copies the other. If both exist, take the sorted union of their children's keys and recurse on each key.
Hint 2
Do the sorting inside the encoder too, so the output is canonical for any tree, including the decoded one.
Hint 3
Parse with recursive descent and a shared index. Check each expected character exactly: key, colon, optional minus, ASCII digits, open bracket, comma-separated children, close bracket. Afterwards the index must equal the string length.
Hint 4
Watch the subtle rejections: duplicate sibling keys (track a set per node), trailing commas, a bare minus sign, and Unicode digits that int() would accept. Also raise the recursion limit for depth up to 1000.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has three independent parts: a recursive merge, a canonical encoder, and a strict parser.
Merge. Convert each input dictionary into node objects, then merge with a helper that takes two optional nodes.
- If both are missing, return
None. - If one is missing, build a fresh copy of the other by recursing into each child with
Noneas the partner. - If both exist, their keys must match, otherwise raise
ValueError. Build a key-to-child map for each side, take the sorted union of keys, and recurse on each key. A key missing on one side becomesNone, which triggers a copy. The new node's value is the sum of the two values.
Since children are paired by key, only the roots can ever mismatch. Every output node is newly constructed, so the inputs are never mutated.
Encode. Write # for None. Otherwise write key:val[ followed by the encoded children, sorted by key and joined with commas, then ]. Sorting inside the encoder makes the output canonical for any tree, including the decoded one.
Decode. A recursive-descent parser walks the string with a shared index. The input # yields None. For a node it:
- reads the key up to one of
:[],, which must be non-empty and followed by:, - reads an optional
-and then at least one ASCII digit (the ASCII check blocks Unicode digits thatint()would accept), - requires
[, - reads zero or more children separated by commas, rejecting duplicate sibling keys with a per-node set, and a trailing or leading comma falls out naturally because a child parse fails on
,or], - requires
].
After the root is parsed, the index must equal the string length, otherwise there are trailing characters.
Why it is correct
- Matching keys are summed and merged recursively, and one-sided keys are copied whole, which is exactly the merge specification.
- Sorting the union of keys, plus sorting again in the encoder, guarantees alphabetical children everywhere.
- Each grammar production checks the exact character it expects, so every malformed form listed in the statement raises
ValueError, and valid forms (including negative numbers, zero, and leading zeros) parse to the right values. Re-encoding normalizes leading zeros.
Complexity
Let N be the total number of nodes and L the length of encoded.
- Merge: O(N log N) time because of sorting each node's child keys, O(N) space plus recursion depth.
- Encode: O(N log N + output length) time.
- Decode: O(L) time, O(N + depth) space.
Recursion depth reaches about 1000, so the recursion limit is raised.
Reference solution
import sys
from typing import Dict, List, Optional
sys.setrecursionlimit(20000)
class Node:
def __init__(self, key, val, children=None):
self.key = key
self.val = val
self.children = children if children is not None else []
def _from_dict(tree):
if tree is None:
return None
return Node(tree['key'], tree['val'],
[_from_dict(c) for c in tree.get('children', [])])
def _merge(a, b):
if a is None:
if b is None:
return None
return Node(b.key, b.val, [_merge(None, c) for c in b.children])
if b is None:
return Node(a.key, a.val, [_merge(c, None) for c in a.children])
if a.key != b.key:
raise ValueError('root keys do not match')
left = {c.key: c for c in a.children}
right = {c.key: c for c in b.children}
children = [_merge(left.get(k), right.get(k))
for k in sorted(left.keys() | right.keys())]
return Node(a.key, a.val + b.val, children)
def _encode(node):
if node is None:
return '#'
kids = sorted(node.children, key=lambda c: c.key)
return f"{node.key}:{node.val}[{','.join(_encode(c) for c in kids)}]"
def _decode(data):
if data == '#':
return None
i = 0
n = len(data)
def parse():
nonlocal i
start = i
while i < n and data[i] not in ':[],':
i += 1
key = data[start:i]
if not key or i >= n or data[i] != ':':
raise ValueError('malformed node key')
i += 1
start = i
if i < n and data[i] == '-':
i += 1
digit_start = i
while i < n and data[i].isdigit() and data[i].isascii():
i += 1
if digit_start == i:
raise ValueError('invalid integer')
val = int(data[start:i])
if i >= n or data[i] != '[':
raise ValueError('missing opening bracket')
i += 1
children = []
seen = set()
if i < n and data[i] != ']':
while True:
child = parse()
if child.key in seen:
raise ValueError('duplicate sibling key')
seen.add(child.key)
children.append(child)
if i >= n:
raise ValueError('missing closing bracket')
if data[i] == ']':
break
if data[i] != ',':
raise ValueError('expected comma')
i += 1
if i >= n or data[i] != ']':
raise ValueError('missing closing bracket')
i += 1
return Node(key, val, children)
root = parse()
if i != n:
raise ValueError('trailing characters')
return root
def combine_config_trees(first: Optional[Dict], second: Optional[Dict], encoded: str) -> List[str]:
merged = _merge(_from_dict(first), _from_dict(second))
decoded = _decode(encoded)
return [_encode(merged), _encode(decoded)]