Diff Two Versions of a Keyed Hierarchy
Trees & GraphsAuto-graded · 18 test casesLast updated
Compare two keyed N-ary trees given as nested dicts and count nodes that were added, removed, given a new value, or attached to a different parent.
You are given two snapshots of a hierarchy: an earlier one (before) and a later one (after). Each snapshot is either None (an empty hierarchy) or a nested dictionary describing a rooted tree with any number of children per node.
Every node is a dictionary with these fields:
"key": a string that identifies the node."value": an integer payload."children": a list of node dictionaries (possibly empty). The field may be missing, in which case the node has no children.
Within a single snapshot, all keys are distinct, so a key identifies one node across both snapshots. The root of a snapshot has no parent (treat its parent as None).
Task
Return the number of nodes that are changed in the later snapshot compared with the earlier one. A key counts as changed if any of the following holds:
- Removed: the key appears in
beforebut not inafter. - Added: the key appears in
afterbut not inbefore. - Value differs: the key appears in both, but its
"value"is different. - Reparented: the key appears in both with equal values, but its parent's key differs between the snapshots. A root has parent
None, so a node that was the root in one snapshot and has a parent key in the other is reparented.
Each key is counted at most once, even if it satisfies several conditions (for example, both a new value and a new parent). Only the node's own parent matters: when a node moves, its descendants whose parent keys are unchanged are not counted for that reason. The order of children in a list has no effect on the result.
Constraints
- Either input may be
None; if both areNonethe answer is0. - Keys are unique within each snapshot.
- Values are integers; keys are strings.
- The number of nodes in each tree can be large (up to roughly 10^5), and a tree may be very deep, so avoid relying on deep recursion.
- Aim for time linear in the total number of nodes.
Examples
Example 1
Input: count_changed_nodes({'key': 'root', 'value': 1, 'children': [{'key': 'a', 'value': 2, 'children': []}]}, {'key': 'root', 'value': 1, 'children': [{'key': 'a', 'value': 3, 'children': []}, {'key': 'b', 'value': 4, 'children': []}]})
Output: 2
Example 2
Input: count_changed_nodes({'key': 'root', 'value': 1, 'children': [{'key': 'a', 'value': 2, 'children': []}, {'key': 'b', 'value': 4, 'children': []}]}, {'key': 'root', 'value': 1, 'children': [{'key': 'b', 'value': 4, 'children': []}, {'key': 'a', 'value': 2, 'children': []}]})
Output: 0
Example 3
Input: count_changed_nodes({'key': 'root', 'value': 1, 'children': [{'key': 'a', 'value': 2, 'children': []}]}, {'key': 'root', 'value': 1, 'children': [{'key': 'b', 'value': 2, 'children': [{'key': 'a', 'value': 2, 'children': []}]}]})
Output: 2
Hints
Hint 1
Whatever the tree shape, each node's relevance to the answer comes down to three facts: whether it exists, its value, and its parent's key.
Hint 2
Flatten each snapshot into a dictionary from key to (value, parent_key) using an iterative traversal with an explicit stack.
Hint 3
Walk over the union of keys from both dictionaries once: a key missing from either side is changed; otherwise it is changed exactly when the two (value, parent_key) tuples differ.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The structure of a tree matters here only through three facts per node: whether the node exists, its value, and its parent's key. So we flatten each snapshot into a dictionary:
key -> (value, parent_key)
The root gets parent None. We build the dictionaries with an iterative depth-first traversal (an explicit stack), which avoids recursion limits on very deep, chain-like trees.
Then we compare the two dictionaries over the union of their keys:
- Key in only one dictionary: it was removed or added, so it is changed.
- Key in both: it is changed exactly when the
(value, parent_key)tuples differ. Tuple inequality covers "value differs", "parent differs", and "both differ" in a single check, so each key is counted once.
Why it is correct
Each of the four change conditions depends only on presence, value, and parent key, and the dictionaries store exactly that information with one entry per node (keys are unique). The keys split into three disjoint groups: only in before, only in after, and in both. Every changed node falls in exactly one group and is counted once; unchanged nodes are never counted. Children order does not influence the dictionaries, so reordering yields 0. A moved node's descendants keep their parent keys, so only the moved node itself is counted.
Complexity
Let n and m be the node counts of the two trees.
- Time: O(n + m) average, since each node is visited once and dictionary operations are O(1) on average (plus the cost of hashing key strings).
- Space: O(n + m) for the dictionaries and the traversal stack.
Reference solution
from typing import Dict, Optional, Tuple
def count_changed_nodes(before: Optional[Dict], after: Optional[Dict]) -> int:
def flatten(root):
info: Dict[str, Tuple[int, Optional[str]]] = {}
if root is None:
return info
stack = [(root, None)]
while stack:
node, parent_key = stack.pop()
key = node["key"]
info[key] = (node["value"], parent_key)
for child in node.get("children", []):
stack.append((child, key))
return info
old_nodes = flatten(before)
new_nodes = flatten(after)
changed = 0
for key in set(old_nodes) | set(new_nodes):
if key not in old_nodes or key not in new_nodes:
changed += 1
elif old_nodes[key] != new_nodes[key]:
changed += 1
return changed