Hash-Tree Diff: Detect File Changes Between Two Snapshots
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests ability to build a bottom-up Merkle hash tree from file path/content mappings and use subtree hash pruning to efficiently classify added, modified, and deleted files.
Background
A hash tree (sometimes called a Merkle tree) is a structure where every leaf stores a hash of a file's content, and every internal node stores a hash derived from its children's names and hashes. Because a subtree's hash changes whenever anything inside it changes, you can detect all differences between two snapshots by walking only the nodes whose hashes diverge — skipping every unchanged subtree entirely.
Task
Write a function that takes two flat dictionaries mapping relative file paths to file contents, then returns a summary of everything that changed between them.
The return value must be a dictionary with exactly three keys:
"root_hash"— the SHA-256 hex digest of the base tree's root directory, or""if the base snapshot is empty."target_root_hash"— the same for the target snapshot."diff"— a dictionary with keys"added","modified", and"deleted", each holding a sorted list of relative file paths:- added: paths that exist only in the target.
- modified: paths present in both snapshots but with different content.
- deleted: paths that exist only in the base.
Hashing Rules
All hashing uses hashlib.sha256(data.encode('utf-8')).hexdigest().
File hash — hash the raw file content string directly.
Directory hash — collect the immediate children of the directory, sort them alphabetically by name, format each as "name:hash", join the entries with "\n", then hash that joined string.
Directories without any files underneath them do not exist in this representation; they arise only because files live inside them.
Diffing Rules
When comparing two corresponding nodes:
- If both nodes have the same hash, their subtrees are identical — stop immediately and do not inspect children.
- If both are files with different hashes, record the path as modified.
- If a path is a file in one tree and a directory in the other, treat every file reachable under the directory side as added or deleted (as appropriate), and treat the file-side path itself as the counterpart deletion or addition.
- If both sides are directories, take the union of their child names:
- A name only in the base → everything under it is deleted.
- A name only in the target → everything under it is added.
- A name in both → recurse.
Constraints
- File paths use forward slashes (
/) only, with no leading or trailing slashes and no.or..segments. - Each snapshot contains at most 10 000 files.
- Maximum directory depth is 20.
- File contents and path segments are non-empty UTF-8 strings.
- A single snapshot will not contain both a path
"a"and a path"a/b"(no file/directory name conflict within one snapshot).
Examples
Example 1
Input: compare_file_snapshots({'src/index.js': 'console.log(1);', 'package.json': '{}'}, {'src/index.js': 'console.log(2);', 'src/utils.js': 'export const x = 1;', 'package.json': '{}'})
Output: {'root_hash': '15bb3841dd6cc3869f92c8d5fa52d5b76cc48338685bebf7df0f496ff50de938', 'target_root_hash': '623d3f3b7ddc5c66dbad9903c5c78c69b8141446f4feca35efbf7ea9e2ce9270', 'diff': {'added': ['src/utils.js'], 'modified': ['src/index.js'], 'deleted': []}}
Hints
Hint 1
Build a trie from each flat path dictionary by splitting on '/'. Intermediate segments become directory nodes; the final segment becomes a file leaf. Compute hashes bottom-up: hash file content directly, then hash each directory by sorting its children's (name, hash) pairs and joining with newlines before hashing.
Hint 2
For the diff, walk both tries together recursively. If the two current nodes share the same hash, return immediately — you don't need to look at anything below. Only when hashes differ do you need to check what kind of node each side is (file vs. directory) and recurse into children.
Hint 3
Handle the empty-snapshot edge cases separately: if the base is empty, every file in the target is 'added'; if the target is empty, every file in the base is 'deleted'. Also remember that when a file and a directory occupy the same name across snapshots, you must collect all reachable files on the directory side rather than treating it as a single modification.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two independent phases: building a hash tree for each snapshot, then walking both trees together to find what changed.
Phase 1 — Build the trie and hash bottom-up
Parse each flat path dictionary into a trie by splitting every path on "/". Intermediate segments become directory nodes (represented as {"children": {...}}); the final segment becomes a file leaf (represented as {"file_hash": <hash>}). Because a directory node is only created when a file lives somewhere beneath it, the "no empty directories" rule holds automatically.
After inserting all paths, compute hashes in a single post-order traversal:
- A file node's hash is
sha256(content). - A directory node's hash is built by sorting its immediate children by name, formatting each as
"name:child_hash", joining all entries with"\n", then hashing the result. Sorting makes the hash deterministic regardless of insertion order, and including names means that renaming a file changes every ancestor hash all the way to the root.
An empty snapshot returns None and the empty string "" as its root hash, satisfying the edge-case requirement without computing sha256("").
Phase 2 — Diff with subtree pruning
Walk both tries together recursively with a shared path prefix string.
Pruning rule: if the two nodes at the current position have the same hash, their entire subtrees are identical. Return immediately.
When hashes differ, check what each side is:
- File vs. file → the path is modified.
- File on one side, directory on the other → the file-side path is deleted/added as a single entry, and every file reachable under the directory side is added/deleted. This correctly handles cases where a file is replaced by a whole directory tree.
- Directory vs. directory → take the union of child names. A name only in base means everything under it is deleted; a name only in target means everything under it is added; a name in both means recurse. The helper
collect_pathsdoes a full subtree traversal to enumerate every file when a whole subtree is added or deleted.
After all recursive calls, sort each of the three output lists.
Why it is correct
Hash soundness guarantees that equal hashes imply equal subtrees (under the SHA-256 collision assumption), so pruning never misses a real change. Sorting children before hashing makes every hash deterministic. The union-of-children walk ensures no path is overlooked: every path that exists in only one tree is reported, and every path present in both is recursively compared. Checking node types before comparing hashes prevents a theoretical scenario where a file's content happens to produce the same hash as some directory's computed string.
Complexity
Let N be the total number of files across both snapshots and L the total length of all path strings.
- Build: O(L) to parse paths into the trie. Hashing all file contents and directory entries is O(C + N) where C is total content size. Sorting children across all directories costs at most O(N log N) in aggregate.
- Diff: O(N) in the worst case (everything changed). In the common case of a small edit, the cost is proportional to the number of directories on the path from the root to the changed files, since unchanged subtrees are pruned in O(1).
- Space: O(N + L) for the two tries, plus O(depth) for the recursion stack (depth ≤ 20).
Edge cases
- Both snapshots identical: root hashes match, so the diff does O(1) work and returns three empty lists.
- One snapshot empty: handled before the recursive walk; all files go into added or deleted.
- File replaced by directory (or vice versa): the type-mismatch branch collects all reachable files on the directory side, so every affected path is reported correctly.
- Root-level files: the prefix starts as
"", so root-level names are formatted without a leading slash.
Reference solution
import hashlib
from typing import Dict
def compare_file_snapshots(base_files: Dict[str, str], target_files: Dict[str, str]) -> Dict[str, object]:
def sha256(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def build(files: Dict[str, str]):
"""Return (root_node_or_None, root_hash_str)."""
root = {"children": {}}
for path, content in files.items():
parts = path.split("/")
node = root
for part in parts[:-1]:
node = node["children"].setdefault(part, {"children": {}})
node["children"][parts[-1]] = {"file_hash": sha256(content)}
def compute_hashes(node):
if "file_hash" in node:
node["hash"] = node["file_hash"]
return node["hash"]
entries = []
for name in sorted(node["children"]):
child_hash = compute_hashes(node["children"][name])
entries.append(f"{name}:{child_hash}")
node["hash"] = sha256("\n".join(entries))
return node["hash"]
if not files:
return None, ""
compute_hashes(root)
return root, root["hash"]
base_root, base_hash = build(base_files)
target_root, target_hash = build(target_files)
added: list = []
modified: list = []
deleted: list = []
def collect_paths(node, prefix: str, output: list) -> None:
if "file_hash" in node:
output.append(prefix)
return
for name, child in node["children"].items():
collect_paths(child, f"{prefix}/{name}" if prefix else name, output)
def diff_nodes(base, target, prefix: str = "") -> None:
if base["hash"] == target["hash"]:
return
base_is_file = "file_hash" in base
target_is_file = "file_hash" in target
if base_is_file and target_is_file:
modified.append(prefix)
return
if base_is_file:
deleted.append(prefix)
collect_paths(target, prefix, added)
return
if target_is_file:
added.append(prefix)
collect_paths(base, prefix, deleted)
return
base_children = base["children"]
target_children = target["children"]
for name in base_children.keys() | target_children.keys():
child_path = f"{prefix}/{name}" if prefix else name
if name not in base_children:
collect_paths(target_children[name], child_path, added)
elif name not in target_children:
collect_paths(base_children[name], child_path, deleted)
else:
diff_nodes(base_children[name], target_children[name], child_path)
if base_root is None:
if target_root is not None:
collect_paths(target_root, "", added)
elif target_root is None:
collect_paths(base_root, "", deleted)
else:
diff_nodes(base_root, target_root)
return {
"root_hash": base_hash,
"target_root_hash": target_hash,
"diff": {
"added": sorted(added),
"modified": sorted(modified),
"deleted": sorted(deleted),
},
}