Count Node Changes Between Two Keyed Hierarchies
Trees & GraphsAuto-graded · 18 test casesLast updated
Compare two keyed trees in parallel and count changed nodes, where a changed value replaces its whole subtree and unmatched nodes count with their subtrees.
Counting Changes Between Two Hierarchies
A hierarchy is stored as nested dictionaries. Each node has this form:
{"key": <string>, "value": <any JSON value>, "children": [<node>, ...]}
An empty hierarchy is None. Among siblings, every key is distinct. The order of a node's children carries no meaning.
You are given two hierarchies, left and right. Return the total number of nodes that differ between them, using the rules below.
Rules
A node is identified by its path: the sequence of keys leading from the root down to that node. Two nodes in different trees are the "same position" only when their paths are identical.
- Only on one side. If a node's path exists in just one tree, that node counts as one change, and every node beneath it in that tree counts too (the whole subtree).
- Same path, different value. If both trees have a node at the same path but their
valuefields are not equal, treat the whole subtree as removed and rebuilt. Add the number of nodes in the left subtree plus the number of nodes in the right subtree. Do not look at descendants separately: nodes below it count even if they look identical on both sides. - Same path, equal value. The node itself adds nothing. Compare its children using these same rules, matching children by key regardless of order.
- Roots. The two roots are compared as being at the same position. If one tree is
None, the answer is the node count of the other tree (0 if both areNone). If both roots exist but have different keys, treat that as the "different value" case: the answer is the sum of both tree sizes.
A missing "value" or "children" entry may be treated as None and as an empty list respectively. Values are compared with Python ==/!=.
Task
Implement the function so it returns the total number of differing nodes as an integer.
Constraints
- Each tree has up to roughly 10^5 nodes; trees can be very deep (a long chain), so avoid relying on Python's recursion limit.
- Sibling keys are unique within each tree.
- Keys are strings; values are arbitrary JSON values.
- The input must not be modified.
Examples
Example 1
Input: count_tree_changes(None, {'key': 'root', 'value': 1, 'children': []})
Output: 1
Example 2
Input: count_tree_changes({'key': 'root', 'value': 'v', 'children': [{'key': 'a', 'value': 1, 'children': []}, {'key': 'b', 'value': 2, 'children': []}]}, {'key': 'root', 'value': 'v', 'children': [{'key': 'b', 'value': 2, 'children': []}, {'key': 'c', 'value': 3, 'children': []}]})
Output: 2
Example 3
Input: count_tree_changes({'key': 'root', 'value': 1, 'children': [{'key': 'a', 'value': 10, 'children': [{'key': 'x', 'value': 1, 'children': []}]}]}, {'key': 'root', 'value': 2, 'children': [{'key': 'a', 'value': 99, 'children': [{'key': 'x', 'value': 1, 'children': []}, {'key': 'y', 'value': 2, 'children': []}]}]})
Output: 7
Example 4
Input: count_tree_changes({'key': 'old', 'value': 0, 'children': [{'key': 'a', 'value': 1, 'children': []}]}, {'key': 'new', 'value': 0, 'children': [{'key': 'b', 'value': 2, 'children': []}]})
Output: 4
Hints
Hint 1
Think of the traversal as walking pairs of nodes that sit at the same key path in both trees. A pair can also have one side missing.
Hint 2
When a pair is missing one side, or the values (or root keys) differ, you add subtree sizes and stop descending. Only when the values match do you go on to the children.
Hint 3
Index each node's children by key in a dictionary, then look at the union of keys. Use an explicit stack and compute subtree sizes iteratively so deep chains don't overflow recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk both trees together, one pair of nodes per key path. Each pair (a, b) is handled like this:
- If
ais missing, add the size ofb's subtree. Ifbis missing, add the size ofa's subtree. - If both exist but the keys or values differ, add
size(a) + size(b)and do not descend. - If both exist and match, index each side's children by key, and push a pair for every key in the union of the two key sets (using
Nonefor the missing side).
Subtree sizes are computed up front for each tree with an iterative post-order pass, stored in a dictionary keyed by id(node). Looking up a size is then O(1).
Why it is correct
Every node in either tree falls into exactly one category:
- It lies in a region reached by the paired walk through matching ancestors. If its own pair matches, it contributes 0 and its children are examined.
- It lies below a pair whose values differ. It is counted once through the sizes added at that pair, and the walk never descends there, so it is not counted again.
- It lies below the point where one side has no node for a key. It is counted once through the size added at that point.
These regions are disjoint and cover both trees, so the total equals the required number of changes. Matching children by key makes the result independent of child order. Root rules (a None root, or differing root keys) fall out of the same pair handling.
Complexity
With n and m the node counts of the two trees, the size pass is O(n + m). The paired walk visits each node at most once, and building the child dictionaries costs time proportional to the number of children. Total time is O(n + m). Space is O(n + m) for the size tables and the explicit stack. Using explicit stacks avoids recursion limits on very deep trees.
Reference solution
from typing import Optional, Dict
def count_tree_changes(left: Optional[Dict], right: Optional[Dict]) -> int:
def subtree_sizes(root):
if root is None:
return {}
sizes = {}
stack = [(root, False)]
while stack:
node, visited = stack.pop()
marker = id(node)
if not visited:
stack.append((node, True))
for child in node.get("children", []):
stack.append((child, False))
else:
sizes[marker] = 1
for child in node.get("children", []):
sizes[marker] += sizes[id(child)]
return sizes
left_sizes = subtree_sizes(left)
right_sizes = subtree_sizes(right)
def size(node, sizes):
return 0 if node is None else sizes[id(node)]
total = 0
pending = [(left, right)]
while pending:
a, b = pending.pop()
if a is None:
total += size(b, right_sizes)
continue
if b is None:
total += size(a, left_sizes)
continue
if a["key"] != b["key"] or a.get("value") != b.get("value"):
total += size(a, left_sizes) + size(b, right_sizes)
continue
left_children = {child["key"]: child for child in a.get("children", [])}
right_children = {child["key"]: child for child in b.get("children", [])}
keys = set(left_children) | set(right_children)
for key in keys:
pending.append((left_children.get(key), right_children.get(key)))
return total