Diff Two Versions of a Configuration Tree
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests recursive-free N-ary tree traversal and set-based diffing to count nodes added, removed, or modified between two tree snapshots.
Problem Statement
A software deployment system tracks application configuration as a versioned tree. Each node in the tree represents a configuration entry and carries three fields:
"id"— a unique integer identifier, stable across versions"value"— the entry's current setting (a string, number, orNone)"children"— a list of child nodes (may be absent on leaf nodes)
You are given two snapshots of this tree: snapshot_a (the earlier version) and snapshot_b (the later version). Write a function that returns the total number of affected nodes when going from snapshot_a to snapshot_b.
A node is affected if any of the following is true:
- Modified — the node appears in both snapshots but its
valuediffers. - Added — the node appears in
snapshot_bbut not insnapshot_a. - Removed — the node appears in
snapshot_abut not insnapshot_b.
Two nodes are considered the same node when they share the same id. You may assume that if an id exists in both snapshots, it occupies the same position in the hierarchy — nodes never migrate to a different parent.
Implement:
diff_config_trees(snapshot_a, snapshot_b)
Constraints
idvalues are unique across the entire tree (no two nodes in the same snapshot share anid).- The total number of nodes across both snapshots is at most 2 × 10⁵.
- The tree is N-ary: a node can have any number of children.
- Either snapshot may be
None(representing an empty configuration). - A node's
"children"key may be omitted entirely; treat it as an empty list. - A node's
"value"key may be omitted; treat it asNone. Two nodes that both have no value are considered equal. - Values are compared with Python's
!=operator. Type differences (e.g.,"10"vs10) count as a modification. - Trees can be deeply nested (chains of up to 10⁵ nodes), so solutions relying on Python's default recursion stack may fail.
Examples
Example 1
Input: diff_config_trees({'id': 1, 'value': 'Pizza', 'children': []}, {'id': 1, 'value': 'Pepperoni Pizza', 'children': []})
Output: 1
Example 2
Input: diff_config_trees({'id': 1, 'children': [{'id': 2, 'value': 'Coke', 'children': []}]}, {'id': 1, 'children': []})
Output: 1
Hints
Hint 1
Instead of diffing the trees structurally, think about what information you actually need per node. The stable-id guarantee means you only need to know, for each id, what value it held in each snapshot — the parent-child relationships are irrelevant to the count.
Hint 2
Flatten each snapshot into a dictionary mapping id → value using an explicit stack (not recursion). Then the problem becomes: how many keys in the union of the two dictionaries have different or missing entries?
Hint 3
Iterating over old_dict.keys() | new_dict.keys() visits every id exactly once. For each id, one of four situations holds: present in both with equal values (unchanged), present in both with different values (modified), only in the old dict (removed), or only in the new dict (added). Only the last three contribute to your count.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight: reduce the tree problem to a map problem
Because every id is unique and stable (nodes never move), the parent-child structure carries no information relevant to the count. The only thing that matters for each node is: does this id exist in snapshot A, in snapshot B, both, or neither — and if both, are the values the same?
That means we can throw away the tree structure entirely and work with two flat dictionaries.
Algorithm
-
Flatten each snapshot into a dictionary
{id: value}by traversing every node with an explicit stack. An explicit stack (rather than recursion) is essential here: Python's default call stack is around 1 000 frames, and the tree can be a chain of 10⁵ nodes. -
Take the set union of all ids across both dictionaries. Every id in either snapshot appears exactly once in this union.
-
Count affected ids — those where at least one of these is true:
- the id is absent from the old dict (an addition),
- the id is absent from the new dict (a removal),
- both dicts have the id but the values differ (a modification).
Why this is correct
Every node falls into exactly one of four buckets:
| In old? | In new? | Values equal? | Affected? |
|---|---|---|---|
| yes | yes | yes | no |
| yes | yes | no | yes — modified |
| yes | no | — | yes — removed |
| no | yes | — | yes — added |
Iterating over the key union visits each id exactly once, so there is no double counting and no id is missed.
Edge cases
- Both snapshots
None: both dicts are empty, union is empty, result is0. - One snapshot
None: every node in the other snapshot is either a pure addition or a pure removal, so the result equals that snapshot's node count. - Missing
"value"key:.get("value")returnsNone. Two nodes that both omit the key compare asNone == Noneand are treated as unchanged. - Missing
"children"key:.get("children", [])returns an empty list; the node is treated as a leaf. - Deep chains: the explicit stack keeps traversal in O(N) heap memory and avoids any recursion limit.
- Type mismatches like
"10"vs10: Python's!=treats these as different, so they are counted as a modification.
Complexity
- Time: O(N₁ + N₂) — each node is pushed and popped from the stack once; each id causes O(1) expected work in the hash-based set union and dictionary lookups.
- Space: O(N₁ + N₂) — for the two flat dictionaries and the union key set. The traversal stack holds at most O(N) entries at a time.
Reference solution
from typing import Dict
def diff_config_trees(snapshot_a: Dict, snapshot_b: Dict) -> int:
def collect(root):
"""Flatten a tree into {id: value} using an explicit stack."""
nodes = {}
if root is None:
return nodes
stack = [root]
while stack:
node = stack.pop()
nodes[node["id"]] = node.get("value")
stack.extend(node.get("children", []))
return nodes
old_nodes = collect(snapshot_a)
new_nodes = collect(snapshot_b)
return sum(
1
for node_id in old_nodes.keys() | new_nodes.keys()
if node_id not in old_nodes # added in new snapshot
or node_id not in new_nodes # removed from old snapshot
or old_nodes[node_id] != new_nodes[node_id] # value was modified
)