KatInterview

Combine Config Trees and Parse a Canonical Encoding

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstreerecursionparsing

Last 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:

  1. Merge first and second into a new tree. Neither input may be modified.
  2. Decode encoded into a tree.
  3. 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 is None.
  • 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 val is 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

  • None is 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 written key: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[],] or a: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 0 and 10^4 nodes.
  • Keys have length 1 to 32 and are alphanumeric in the input trees. Sibling keys in the input trees are unique.
  • Values satisfy -10^6 <= val <= 10^6 in 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.