Detect File Changes Using Content-Based Tree Hashing
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests hierarchical hashing, tree traversal, and efficient change detection across nested directory structures
You are building a version control tool that tracks changes between two repository snapshots. Each snapshot is represented as a dictionary mapping file paths to their contents.
Your task is to construct a content-addressable tree structure where:
- Each file is represented by a hash of its contents
- Each directory is represented by a hash computed from its children's names, types, and hashes
- The hash computation must be deterministic (sorted by child name)
Using this tree structure, efficiently identify all files that were added, removed, or modified between two snapshots.
Implement the function:
def detect_file_changes(snapshot_a: Dict[str, str], snapshot_b: Dict[str, str]) -> List[List[str]]
Parameters:
snapshot_a: Dictionary mapping file paths to content strings (first snapshot)snapshot_b: Dictionary mapping file paths to content strings (second snapshot)
Returns:
- List of changes, where each change is
[path, change_type] change_typeis one of:"ADDED","REMOVED", or"MODIFIED"- Results must be sorted by path in lexicographic order
Path Format:
- Paths use forward slashes as separators (e.g.,
"src/main.py") - Paths are relative and do not start with
/ - Each path component must be non-empty
Change Classification:
ADDED: File exists insnapshot_bbut not insnapshot_aREMOVED: File exists insnapshot_abut not insnapshot_bMODIFIED: File exists in both snapshots with different contents
Edge Cases:
- If a path changes from file to directory (or vice versa), treat the old files as
REMOVEDand new files asADDED - If two directories have identical hashes, their entire subtrees are identical and can be skipped
- Empty snapshots are valid inputs
- Duplicate or conflicting paths (e.g., both
"src"as a file and"src/main.py") should raiseValueError
Constraints
- 0 ≤ total files across both snapshots ≤ 10,000
- 0 ≤ file content length ≤ 1 MB
- 1 ≤ path component length ≤ 255
- Path depth ≤ 100
- Use SHA-256 for hashing
- Only report file-level changes (not directories)
Examples
Example 1
Input: detect_file_changes({}, {})
Output: []
Example 2
Input: detect_file_changes({'src/main.py': 'print(\'hello\')'}, {'src/main.py': 'print(\'world\')', 'README.md': 'Intro'})
Output: [['README.md', 'ADDED'], ['src/main.py', 'MODIFIED']]
Example 3
Input: detect_file_changes({'old.txt': 'data', 'src/a.py': 'a'}, {'src/a.py': 'a', 'new.txt': 'data'})
Output: [['new.txt', 'ADDED'], ['old.txt', 'REMOVED']]
Hints
Hint 1
Build an n-ary tree mirroring the directory hierarchy, where internal nodes are folders and leaves are files
Hint 2
Hash each file's content with a type prefix; hash each directory by combining sorted children (name + type + hash)
Hint 3
During diff, compare directory hashes first—if equal, skip the entire subtree to avoid unnecessary comparisons
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution builds a hierarchical tree structure that mirrors the directory layout, then uses content-based hashing to efficiently detect changes.
Step 1: Build the tree structure
Parse each file path and construct an n-ary tree where:
- Internal nodes represent directories (stored as dictionaries)
- Leaf nodes represent files (stored as hash strings)
- Each file's hash is computed as
SHA256("F\0" + content)
This construction validates paths and detects conflicts where a path component is used as both a file and a directory.
Step 2: Compute directory hashes
For each directory node, compute a hash that depends on all its children:
- Sort children by name (ensures determinism)
- For each child, collect: name, type (
"D"or"F"), and hash - Serialize this list as JSON
- Compute
SHA256("D\0" + serialized_children)
This recursive hashing means that any change in a subtree propagates up to the root. Two directories with identical hashes have identical contents.
Step 3: Diff the trees
Walk both trees simultaneously:
- If both directories have the same hash, skip the entire subtree (they're identical)
- For each name in the union of children:
- Missing in A → recursively mark all files under B's child as
ADDED - Missing in B → recursively mark all files under A's child as
REMOVED - Both are directories → recurse if hashes differ
- Both are files → compare hashes and report
MODIFIEDif different - Type mismatch (file vs directory) → report old files as
REMOVED, new files asADDED
- Missing in A → recursively mark all files under B's child as
The key optimization is hash-based pruning: when directory hashes match, we avoid examining potentially thousands of unchanged files.
Why It Works
Correctness of pruning: The directory hash includes every child's name, type, and content hash in a deterministic order. If any file changes, its hash changes, causing its parent's hash to change, propagating to the root. Therefore, equal hashes guarantee identical subtrees.
Collision resistance: SHA-256 provides sufficient collision resistance for practical repository sizes. The "F\0" and "D\0" prefixes prevent a file whose content happens to match a directory's serialization from producing a hash collision.
Completeness: By iterating over the union of child names in both trees, every file is classified exactly once as added, removed, or modified.
Complexity
Let N = total number of files, D = maximum depth, and B = total bytes of content.
Time: O(N log k + B) where k is the maximum number of children in any directory. Sorting children dominates tree operations. In the worst case (all files changed), we examine every node. In practice, when few files change, hash-based pruning reduces this to O(changed files × D).
Space: O(N) for the tree structures plus O(D) for the recursion stack. The output list is O(number of changes).
Full Solution
import hashlib
import json
from typing import Dict, List
def detect_file_changes(snapshot_a: Dict[str, str], snapshot_b: Dict[str, str]) -> List[List[str]]:
def build_tree(files):
root = {}
for path, content in files.items():
parts = path.strip("/").split("/")
if not parts or not parts[-1]:
raise ValueError("Invalid file path")
node = root
for part in parts[:-1]:
if not part:
raise ValueError("Invalid file path")
if part not in node:
node[part] = {}
elif not isinstance(node[part], dict):
raise ValueError("A path cannot be both a file and a directory")
node = node[part]
name = parts[-1]
if name in node:
raise ValueError("Duplicate or conflicting file path")
node[name] = hashlib.sha256(b"F\0" + content.encode("utf-8")).hexdigest()
return root
def compute_hash(node):
entries = []
for name in sorted(node):
child = node[name]
if isinstance(child, dict):
kind = "D"
child_hash = compute_hash(child)
else:
kind = "F"
child_hash = child
entries.append([name, kind, child_hash])
payload = json.dumps(entries, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(b"D\0" + payload).hexdigest()
tree_a = build_tree(snapshot_a)
tree_b = build_tree(snapshot_b)
if compute_hash(tree_a) == compute_hash(tree_b):
return []
changes = []
def collect_all_files(node, path, change_type):
if isinstance(node, dict):
for name in sorted(node):
child_path = f"{path}/{name}" if path else name
collect_all_files(node[name], child_path, change_type)
else:
changes.append([path, change_type])
def diff_trees(a, b, prefix=""):
for name in sorted(set(a) | set(b)):
path = f"{prefix}/{name}" if prefix else name
in_a = name in a
in_b = name in b
if not in_a:
collect_all_files(b[name], path, "ADDED")
elif not in_b:
collect_all_files(a[name], path, "REMOVED")
elif isinstance(a[name], dict) and isinstance(b[name], dict):
if compute_hash(a[name]) != compute_hash(b[name]):
diff_trees(a[name], b[name], path)
elif isinstance(a[name], dict):
collect_all_files(a[name], path, "REMOVED")
elif isinstance(b[name], dict):
collect_all_files(b[name], path, "ADDED")
elif a[name] != b[name]:
changes.append([path, "MODIFIED"])
diff_trees(tree_a, tree_b)
return changes