Directory-Hierarchy Merkle Tree for Repository Diffing
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given two snapshots of a source repository, build a Merkle tree that mirrors the repository's directory hierarchy and compute all file-level changes between the baseline state snapshot_a and the updated state snapshot_b:
def merkle_repo_diff(snapshot_a: Dict[str, str], snapshot_b: Dict[str, str]) -> List[List[str]]:
Each snapshot is a dictionary mapping POSIX-style relative file paths (segments separated by "/", with no leading or trailing slash) to UTF-8 file contents. Within any single snapshot, no path is simultaneously a file and an ancestor folder of another file.
Your implementation must satisfy these rules:
- Folder-aligned tree structure: Internal nodes correspond to directories and leaf nodes correspond to files along the actual path hierarchy (not a fixed-arity binary tree over flat blocks).
- Deterministic cryptographic hashing: Each file leaf computes its digest from its raw content bytes, and each directory node computes its digest bottom-up from its sorted child entries (including child kind, entry name, and child digest) so that sibling renames, content swaps, and subtree edits always change the parent directory's digest.
- Subtree pruning during diff: Traverse both trees top-down and skip any directory subtree in
O(1)whenever the aligned directory digests match. - File-only change classification: Never emit directory paths in the output. Report each changed file path as
[relative_path, change_type], wherechange_typeis:"ADDED"— path is present insnapshot_bonly."REMOVED"— path is present insnapshot_aonly."MODIFIED"— path is present in both snapshots with different file contents.
- File-to-folder and folder-to-file replacements: If the same path is a regular file in one snapshot and a directory in the other, report
"REMOVED"for every affected file leaf insnapshot_aand"ADDED"for every affected file leaf insnapshot_b. - Output ordering: Return the
[relative_path, change_type]pairs sorted in ascending ASCII order by the fullrelative_pathstring (note that"a.txt"sorts before"a/b"because'.'precedes'/'in ASCII).
Using only the Python standard library, structure your MerkleTree class so it can also index an on-disk checkout directory (MerkleTree(root_directory)) and compare trees via tree_a.diff(tree_b).
Examples
Example 1
Input:
snapshot_a = {"app/server.py": "port = 8000", "lib/math.py": "x = 1"}
snapshot_b = {"app/server.py": "port = 9000", "docs/guide.md": "# Setup", "lib/math.py": "x = 1"}
Output:
[["app/server.py", "MODIFIED"], ["docs/guide.md", "ADDED"]]
Explanation: Folder "lib" has the exact same Merkle digest in both trees and is skipped without inspecting "lib/math.py". "app/server.py" changed contents ("MODIFIED"), and "docs/guide.md" is new ("ADDED").
Example 2
Input:
snapshot_a = {"draft.txt": "notes", "pkg/core/run.py": "pass"}
snapshot_b = {"final.txt": "notes", "pkg/core/run.py": "pass"}
Output:
[["draft.txt", "REMOVED"], ["final.txt", "ADDED"]]
Explanation: Even though "draft.txt" and "final.txt" contain identical text, root directory digests include child entry names, so "draft.txt" is reported as "REMOVED" and "final.txt" as "ADDED", while the unchanged "pkg" subtree is pruned at its root.
Example 3
Input:
snapshot_a = {"config": "env=dev", "index.py": "main()"}
snapshot_b = {"config/db.ini": "host=localhost", "config/cache.ini": "ttl=60", "index.py": "main()"}
Output:
[["config", "REMOVED"], ["config/cache.ini", "ADDED"], ["config/db.ini", "ADDED"]]
Explanation: "index.py" is unchanged. "config" switched from a single file in snapshot_a to a directory of two files in snapshot_b, producing "REMOVED" for "config" and "ADDED" for "config/cache.ini" and "config/db.ini" in sorted path order.
Constraints
0 <= len(snapshot_a), len(snapshot_b) <= 2 * 10^4- Relative paths consist of non-empty segments separated by
"/"(depth1to30). - File content strings have total length up to
10^6characters across a snapshot (and may be empty strings""). - Within a single snapshot, no file path equals a directory prefix of another path in that same snapshot.
- Use only the Python standard library (
hashlib,os,json,enum, etc.).
Step-by-step walkthrough
Understand the goal and repository snapshot shapes
We want to build a Merkle tree that mirrors a repository's real folder structure (folders are internal nodes, files are leaves) and use it to report every file that changed between two snapshots:
ADDED: file path exists only in the new snapshot (snapshot_b/other).REMOVED: file path exists only in the old snapshot (snapshot_a/self).MODIFIED: file path exists in both snapshots, but its contents changed.
On disk,
MerkleTree(root_directory)walks a folder andtree_a.diff(tree_b)returns(relative_path, ChangeType)pairs. In the automated judge,merkle_repo_diff(snapshot_a, snapshot_b)receives two{relative_path: file_text}dictionaries and returns[relative_path, change_string]pairs sorted by path:snapshot_a = {"app/server.py": "port = 8000", "lib/math.py": "x = 1"} snapshot_b = {"app/server.py": "port = 9000", "docs/guide.md": "# Setup", "lib/math.py": "x = 1"} output = [["app/server.py", "MODIFIED"], ["docs/guide.md", "ADDED"]]Two important rules to keep straight from the start:
- Files only: Folders themselves are never listed in the output. If a file
"config"turns into a folder containing"config/db.ini","config"isREMOVEDand"config/db.ini"isADDED. - Full-path string sorting: Output is sorted by the full path string, where
"a.txt"comes before"a/b"because'.'(ASCII 46) sorts before'/'(ASCII 47).
Why a Merkle tree beats flat scanning when subtrees match
If you just have two small dictionaries in memory, comparing keys directly in a flat loop is
O(files)and makes a great test oracle. Why build a Merkle tree—a tree where every file stores a hash of its contents and every folder stores a hash computed from its children's names and hashes?Look at what happens when 1 file changes in a repository of 100,000 files:
root (hash changed!) / \ src/ (hash changed!) vendor/ (10,000 files — SAME hash!) / \ \ main.py util.py [entire subtree skipped in O(1)!] (MODIFIED) (same hash)- Instant subtree pruning: Whenever two folders have the exact same hash, every file and subfolder inside them is guaranteed to be identical, so
diffskips the entire subtree in a single string comparison! - Cheap incremental updates and network sync: Editing one file only requires rehashing the folders along its ancestor chain (
O(depth)), and two machines can sync over a network by exchanging hashes top-down only along branches that disagree.
- Instant subtree pruning: Whenever two folders have the exact same hash, every file and subfolder inside them is guaranteed to be identical, so
Design collision-safe leaf and directory hashes
We use SHA-256 (a standard cryptographic hash function from
hashlibthat turns any byte sequence into a fixed 64-character hex fingerprint where accidental collisions are astronomically unlikely).How should we hash each kind of node so no two distinct repository states ever produce the same hash?
- File leaf (
file_hash): Hash the file's raw bytes, leaving the filename out of the leaf hash itself (so identical files share a hash, useful if you later want rename detection). - Directory node (
compute_directory_hashes): Collect[kind, name, child_hash]for each child in sortednameorder, serialize that list withjson.dumps, and hash it:- Why sort by
name? Directory iteration order (os.listdir) varies across operating systems and filesystems; sorting makes the hash 100% deterministic. - Why include
nameinside the parent's hash? If you hashed only child hashes, renaming"draft.txt"to"final.txt"(same file content) or swapping the contents of"a.txt"and"b.txt"would leave the parent folder's hash unchanged, hiding real changes! - Why
json.dumpsand type tags (b"file\0",b"link\0",b"dir\0")? Putting a domain-separation tag (a distinct byte prefix per node type) in front of the bytes prevents a regular file whose text happens to look like JSON from ever matching a directory's hash, andjson.dumpscleanly escapes quotes, commas, and newlines in filenames.
- Why sort by
class ChangeType(str, Enum): ADDED = "ADDED" MODIFIED = "MODIFIED" REMOVED = "REMOVED" def file_hash(content: bytes) -> str: """Compute SHA-256 of raw file bytes with a domain-separation tag.""" # Prefixing b"file\0" guarantees a regular file hash can never match a folder or symlink hash. return hashlib.sha256(b"file\0" + content).hexdigest() def hashes_from_contents(snapshot: Dict[str, str]) -> Dict[str, str]: """Convert an in-memory {relative_path: text} map into {relative_path: leaf_hash}.""" leaf_hashes: Dict[str, str] = {} for path, text in snapshot.items(): leaf_hashes[path] = file_hash(text.encode("utf-8")) return leaf_hashes- File leaf (
Build the folder hierarchy and hash bottom-up
Unlike a binary Merkle tree over flat blocks, our
Nodemirrors the actual folder tree: each folder keeps a dictionarychildrenmapping child names ("src","main.py") to childNodes.To build the tree from
{relative_path: leaf_hash}:- Split each path on
"/", walk down fromrootcreating missing directory nodes forparts[:-1], and attach a file leaf node atparts[-1]. - Reject impossible inputs where the same path acts as both a file and a folder inside a single snapshot (such as
"lib"and"lib/util.py"). - Compute directory hashes bottom-up (a post-order traversal, where we finish computing every child's hash before computing its parent's hash).
class Node: """A Merkle tree node representing either a file leaf or a directory internal node.""" def __init__(self, is_file: bool, hash_value: str = "") -> None: self.is_file = is_file self.hash = hash_value # children: maps entry_name -> child Node, e.g. {"main.py": Node(is_file=True, ...)}; empty for files. self.children: Dict[str, "Node"] = {} def compute_directory_hashes(node: Node) -> str: """Recursively compute directory hashes bottom-up (post-order) from sorted children.""" if node.is_file: return node.hash # Sort child names so directory hashes do not depend on filesystem or dict insertion order. # Include [kind, name, child_hash] so renames and content swaps between siblings change the parent hash. entries: List[List[str]] = [] for name in sorted(node.children): child = node.children[name] kind = "file" if child.is_file else "dir" child_hash = compute_directory_hashes(child) entries.append([kind, name, child_hash]) # json.dumps unambiguously escapes special characters in filenames; b"dir\0" separates folders from files. serialized = json.dumps(entries).encode("utf-8") node.hash = hashlib.sha256(b"dir\0" + serialized).hexdigest() return node.hash def build_tree(leaf_hashes: Dict[str, str]) -> Node: """Build the folder hierarchy from {relative_path: leaf_hash} and compute all hashes.""" root = Node(is_file=False) for path, leaf_hash in leaf_hashes.items(): parts = path.split("/") node = root # Walk or create every parent folder along the path. for folder in parts[:-1]: if folder not in node.children: node.children[folder] = Node(is_file=False) node = node.children[folder] if node.is_file: raise ValueError(f"{path!r}: a parent folder conflicts with an existing file") file_name = parts[-1] if file_name in node.children: raise ValueError(f"{path!r}: path conflicts with an existing file or folder") node.children[file_name] = Node(is_file=True, hash_value=leaf_hash) compute_directory_hashes(root) return root- Split each path on
Prune unchanged folders and diff top-down
Now
diff_nodes(old, new, path, out)walks both trees together starting at(self.root, other.root, ""). At every path, one of four mutually exclusive cases applies:Case Condition What we do 1. Identical subtrees oldandnewboth exist andold.hash == new.hashReturn immediately (Merkle pruning—skip everything underneath!) 2. Modified file Both exist, both are files ( is_file), hashes differAppend (path, ChangeType.MODIFIED)3. One-sided or type swap One is None, or one is a file and the other is a folderCollect all files under oldasREMOVEDand all files undernewasADDED4. Changed folder Both are folders with different hashes Recurse on every name in set(old.children) \| set(new.children)Look at how cleanly Case 3 handles a file-to-folder replacement at
"lib":old tree: "lib" (file) --> collect_files(old) emits ("lib", REMOVED) new tree: "lib/" -> core.py, util.py --> collect_files(new) emits ("lib/core.py", ADDED), ("lib/util.py", ADDED)def join_path(prefix: str, name: str) -> str: """Join a relative directory prefix and entry name using '/'.""" if prefix == "": return name return prefix + "/" + name def collect_files(node: Node, path: str, change: ChangeType, out: List[Tuple[str, ChangeType]]) -> None: """Emit every file leaf inside a one-sided subtree as ADDED or REMOVED.""" if node.is_file: out.append((path, change)) return for name, child in node.children.items(): collect_files(child, join_path(path, name), change, out) def diff_nodes( old: Optional[Node], new: Optional[Node], path: str, out: List[Tuple[str, ChangeType]], ) -> None: """Compare aligned nodes top-down, pruning any subtree whose Merkle hashes match.""" # Phase 1 — Merkle pruning: identical hashes mean the entire subtrees match; skip below! if old is not None and new is not None and old.hash == new.hash: return # Phase 2 — Both sides are files at the same path, and their hashes differ. if old is not None and new is not None and old.is_file and new.is_file: out.append((path, ChangeType.MODIFIED)) return # Phase 3 — Path exists on only one side, OR switched between file and directory. if old is None or new is None or old.is_file != new.is_file: if old is not None: collect_files(old, path, ChangeType.REMOVED, out) if new is not None: collect_files(new, path, ChangeType.ADDED, out) return # Phase 4 — Both sides are directories with different hashes: recurse into all child names. all_names = set(old.children) | set(new.children) for name in sorted(all_names): diff_nodes(old.children.get(name), new.children.get(name), join_path(path, name), out)Support real on-disk repositories and wrap `MerkleTree`
To run against real checkouts on disk using only the Python standard library,
hashes_from_directorywalks the folder withos.walkand handles three real-world details:- Skip
.git: Removing".git"fromsubfoldersin place preventsos.walkfrom entering Git's internal object database. - Handle symbolic links safely: A symbolic link (symlink) is a special filesystem entry that stores a pointer path to another file or folder rather than regular file contents. Like Git, we never follow symlinks (which could point outside the repo or loop forever); instead we hash their target path with
b"link\0". Becauseos.walkplaces symlinks to folders insidesubfolders, we inspectsubfolderswithos.path.islinktoo. - Read raw bytes (
"rb"): Binary mode hashes exact bytes without Windows/Unix newline translation or UTF-8 decoding errors on images and binaries.
Finally,
MerkleTreeaccepts either a directory path on disk or a pre-hashed map, sortschangesby full path string, andmerkle_repo_diffformats[path, change.value]for the judge.def link_hash(target: bytes) -> str: """Compute SHA-256 of a symlink's target path with its own domain tag.""" # Prefixing b"link\0" ensures replacing a text file "src" with a symlink -> "src" counts as MODIFIED. return hashlib.sha256(b"link\0" + target).hexdigest() def hashes_from_directory(root_directory: str) -> Dict[str, str]: """Walk a real checkout on disk and return {posix_relative_path: leaf_hash}.""" leaf_hashes: Dict[str, str] = {} for folder, subfolders, file_names in os.walk(root_directory): # Mutating subfolders in place tells os.walk not to descend into Git's internal metadata. if ".git" in subfolders: subfolders.remove(".git") names = list(file_names) for name in subfolders: # os.walk places symlinks to folders in subfolders without entering them; treat them as leaves. if os.path.islink(os.path.join(folder, name)): names.append(name) for name in names: full_path = os.path.join(folder, name) # Normalize OS path separators to "/" so hashes and output paths match across platforms. relative = os.path.relpath(full_path, root_directory).replace(os.sep, "/") if os.path.islink(full_path): target_bytes = os.fsencode(os.readlink(full_path)) leaf_hashes[relative] = link_hash(target_bytes) else: # Read raw bytes ("rb") to avoid newline translation or UTF-8 decode crashes on binary files. with open(full_path, "rb") as f: leaf_hashes[relative] = file_hash(f.read()) return leaf_hashes class MerkleTree: """Directory-hierarchy Merkle tree supporting both disk paths and pre-hashed snapshots.""" def __init__(self, root_or_hashes: Any) -> None: if isinstance(root_or_hashes, str): leaf_hashes = hashes_from_directory(root_or_hashes) else: leaf_hashes = root_or_hashes self.root = build_tree(leaf_hashes) @classmethod def from_snapshot(cls, snapshot: Dict[str, str]) -> "MerkleTree": """Build a MerkleTree from an in-memory {relative_path: content} dictionary.""" return cls(hashes_from_contents(snapshot)) def diff(self, other: "MerkleTree") -> List[Tuple[str, ChangeType]]: """Return (relative_path, ChangeType) for all changed files, sorted by path.""" changes: List[Tuple[str, ChangeType]] = [] diff_nodes(self.root, other.root, "", changes) # Sort by full path string because tree order puts folder "a/b" before sibling "a.txt", # whereas ASCII string order puts "a.txt" before "a/b" ('.' < '/'). changes.sort() return changes def merkle_repo_diff(snapshot_a: Dict[str, str], snapshot_b: Dict[str, str]) -> List[List[str]]: tree_a = MerkleTree.from_snapshot(snapshot_a) tree_b = MerkleTree.from_snapshot(snapshot_b) result: List[List[str]] = [] for path, change in tree_a.diff(tree_b): result.append([path, change.value]) return result- Skip
Trace Example 2 step by step
Let's trace
snapshot_a = {"draft.txt": "notes", "pkg/core/run.py": "pass"}againstsnapshot_b = {"final.txt": "notes", "pkg/core/run.py": "pass"}:Tree A Tree B root (hash H_root_A) root (hash H_root_B != H_root_A) ├── "draft.txt" (file, H("notes")) ├── "final.txt" (file, H("notes")) └── "pkg" (dir, H_pkg) └── "pkg" (dir, H_pkg) └── "core" (dir, H_core) └── "core" (dir, H_core) └── "run.py" (file, H("pass")) └── "run.py" (file, H("pass"))- Root comparison:
H_root_A != H_root_Bbecause root A lists"draft.txt"while root B lists"final.txt", so we inspect the union of child names["draft.txt", "final.txt", "pkg"]. "draft.txt":oldis a file,newisNone-> emits("draft.txt", REMOVED)."final.txt":oldisNone,newis a file -> emits("final.txt", ADDED). Notice"draft.txt"and"final.txt"had the exact same leaf hashH("notes"), yet including child names in root's hash ensured neither change was missed!"pkg": Both trees have folder"pkg"with identical hashH_pkg, so Phase 1 prunes"pkg"immediately without descending into"pkg/core"or"pkg/core/run.py".
Sorting gives
[["draft.txt", "REMOVED"], ["final.txt", "ADDED"]].- Root comparison:
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from enum import Enum import hashlib import json import os class ChangeType(str, Enum): ADDED = "ADDED" MODIFIED = "MODIFIED" REMOVED = "REMOVED" def file_hash(content: bytes) -> str: """Compute SHA-256 of raw file bytes with a domain-separation tag.""" # Prefixing b"file\0" guarantees a regular file hash can never match a folder or symlink hash. return hashlib.sha256(b"file\0" + content).hexdigest() def link_hash(target: bytes) -> str: """Compute SHA-256 of a symlink's target path with its own domain tag.""" # Prefixing b"link\0" ensures replacing a text file "src" with a symlink -> "src" counts as MODIFIED. return hashlib.sha256(b"link\0" + target).hexdigest() def hashes_from_contents(snapshot: Dict[str, str]) -> Dict[str, str]: """Convert an in-memory {relative_path: text} map into {relative_path: leaf_hash}.""" leaf_hashes: Dict[str, str] = {} for path, text in snapshot.items(): leaf_hashes[path] = file_hash(text.encode("utf-8")) return leaf_hashes def hashes_from_directory(root_directory: str) -> Dict[str, str]: """Walk a real checkout on disk and return {posix_relative_path: leaf_hash}.""" leaf_hashes: Dict[str, str] = {} for folder, subfolders, file_names in os.walk(root_directory): # Mutating subfolders in place tells os.walk not to descend into Git's internal metadata. if ".git" in subfolders: subfolders.remove(".git") names = list(file_names) for name in subfolders: # os.walk places symlinks to folders in subfolders without entering them; treat them as leaves. if os.path.islink(os.path.join(folder, name)): names.append(name) for name in names: full_path = os.path.join(folder, name) # Normalize OS path separators to "/" so hashes and output paths match across platforms. relative = os.path.relpath(full_path, root_directory).replace(os.sep, "/") if os.path.islink(full_path): target_bytes = os.fsencode(os.readlink(full_path)) leaf_hashes[relative] = link_hash(target_bytes) else: # Read raw bytes ("rb") to avoid newline translation or UTF-8 decode crashes on binary files. with open(full_path, "rb") as f: leaf_hashes[relative] = file_hash(f.read()) return leaf_hashes class Node: """A Merkle tree node representing either a file leaf or a directory internal node.""" def __init__(self, is_file: bool, hash_value: str = "") -> None: self.is_file = is_file self.hash = hash_value # children: maps entry_name -> child Node, e.g. {"main.py": Node(is_file=True, ...)}; empty for files. self.children: Dict[str, "Node"] = {} def compute_directory_hashes(node: Node) -> str: """Recursively compute directory hashes bottom-up (post-order) from sorted children.""" if node.is_file: return node.hash # Sort child names so directory hashes do not depend on filesystem or dict insertion order. # Include [kind, name, child_hash] so renames and content swaps between siblings change the parent hash. entries: List[List[str]] = [] for name in sorted(node.children): child = node.children[name] kind = "file" if child.is_file else "dir" child_hash = compute_directory_hashes(child) entries.append([kind, name, child_hash]) # json.dumps unambiguously escapes special characters in filenames; b"dir\0" separates folders from files. serialized = json.dumps(entries).encode("utf-8") node.hash = hashlib.sha256(b"dir\0" + serialized).hexdigest() return node.hash def build_tree(leaf_hashes: Dict[str, str]) -> Node: """Build the folder hierarchy from {relative_path: leaf_hash} and compute all hashes.""" root = Node(is_file=False) for path, leaf_hash in leaf_hashes.items(): parts = path.split("/") node = root # Walk or create every parent folder along the path. for folder in parts[:-1]: if folder not in node.children: node.children[folder] = Node(is_file=False) node = node.children[folder] if node.is_file: raise ValueError(f"{path!r}: a parent folder conflicts with an existing file") file_name = parts[-1] if file_name in node.children: raise ValueError(f"{path!r}: path conflicts with an existing file or folder") node.children[file_name] = Node(is_file=True, hash_value=leaf_hash) compute_directory_hashes(root) return root def join_path(prefix: str, name: str) -> str: """Join a relative directory prefix and entry name using '/'.""" if prefix == "": return name return prefix + "/" + name def collect_files(node: Node, path: str, change: ChangeType, out: List[Tuple[str, ChangeType]]) -> None: """Emit every file leaf inside a one-sided subtree as ADDED or REMOVED.""" if node.is_file: out.append((path, change)) return for name, child in node.children.items(): collect_files(child, join_path(path, name), change, out) def diff_nodes( old: Optional[Node], new: Optional[Node], path: str, out: List[Tuple[str, ChangeType]], ) -> None: """Compare aligned nodes top-down, pruning any subtree whose Merkle hashes match.""" # Phase 1 — Merkle pruning: identical hashes mean the entire subtrees match; skip below! if old is not None and new is not None and old.hash == new.hash: return # Phase 2 — Both sides are files at the same path, and their hashes differ. if old is not None and new is not None and old.is_file and new.is_file: out.append((path, ChangeType.MODIFIED)) return # Phase 3 — Path exists on only one side, OR switched between file and directory. if old is None or new is None or old.is_file != new.is_file: if old is not None: collect_files(old, path, ChangeType.REMOVED, out) if new is not None: collect_files(new, path, ChangeType.ADDED, out) return # Phase 4 — Both sides are directories with different hashes: recurse into all child names. all_names = set(old.children) | set(new.children) for name in sorted(all_names): diff_nodes(old.children.get(name), new.children.get(name), join_path(path, name), out) class MerkleTree: """Directory-hierarchy Merkle tree supporting both disk paths and pre-hashed snapshots.""" def __init__(self, root_or_hashes: Any) -> None: if isinstance(root_or_hashes, str): leaf_hashes = hashes_from_directory(root_or_hashes) else: leaf_hashes = root_or_hashes self.root = build_tree(leaf_hashes) @classmethod def from_snapshot(cls, snapshot: Dict[str, str]) -> "MerkleTree": """Build a MerkleTree from an in-memory {relative_path: content} dictionary.""" return cls(hashes_from_contents(snapshot)) def diff(self, other: "MerkleTree") -> List[Tuple[str, ChangeType]]: """Return (relative_path, ChangeType) for all changed files, sorted by path.""" changes: List[Tuple[str, ChangeType]] = [] diff_nodes(self.root, other.root, "", changes) # Sort by full path string because tree order puts folder "a/b" before sibling "a.txt", # whereas ASCII string order puts "a.txt" before "a/b" ('.' < '/'). changes.sort() return changes def merkle_repo_diff(snapshot_a: Dict[str, str], snapshot_b: Dict[str, str]) -> List[List[str]]: tree_a = MerkleTree.from_snapshot(snapshot_a) tree_b = MerkleTree.from_snapshot(snapshot_b) result: List[List[str]] = [] for path, change in tree_a.diff(tree_b): result.append([path, change.value]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine auditing two huge filing cabinets without opening every single paper folder: you stamp every file with a unique fingerprint of its text, then attach a summary card to each folder listing its sorted contents and their fingerprints, and stamp that folder with a fingerprint of its summary card all the way up to the cabinet drawer. That hierarchy of bottom-up fingerprints is a Merkle tree (a tree data structure in which every leaf node holds a cryptographic hash of raw data and every parent node holds a hash derived from its children).
Why not just compare every file path and file body directly? In a 100,000-file repository where only app/server.py changed—or when a local IDE is syncing with a remote server—scanning or transmitting every file wastes work proportional to the entire repository rather than the changed portion. With a Merkle tree, any folder whose fingerprint matches on both sides is guaranteed to be 100% identical all the way down and can be skipped in a single O(1) check.
Walk through Example 2 (snapshot_a = {"draft.txt": "notes", "pkg/core/run.py": "pass"} vs snapshot_b = {"final.txt": "notes", "pkg/core/run.py": "pass"}):
- Hash leaves: Using SHA-256 (a standard hash function turning arbitrary bytes into a 64-character hex digest),
"draft.txt"and"final.txt"both getH("notes"), and"pkg/core/run.py"getsH("pass"). - Hash folders bottom-up: In both snapshots,
"pkg/core"and"pkg"have identical child lists, so both"pkg"nodes get the identical folder hashH_pkg. However, root A hashesdraft.txt+pkgwhile root B hashesfinal.txt+pkg, so the two root hashes differ. - Diff top-down: Because the roots differ, we check
["draft.txt", "final.txt", "pkg"]."draft.txt"exists only in A (REMOVED),"final.txt"exists only in B (ADDED), and"pkg"hasH_pkg == H_pkg—so the entire"pkg"subtree is skipped without ever opening"pkg/core/run.py".
Complexity
Let F be the number of files, B the total bytes across all files, L the sum of path string lengths, D the maximum folder depth, and m the number of changed files.
- Tree construction time:
O(B + L + sum(c log c)), wherecis the number of entries inside each directory. Every file byte is hashed once (O(B)), every path is split and inserted once (O(L)), and each folder sorts itscimmediate child names once during post-order traversal (visiting children before their parent) to compute its folder hash. - Diff time: When trees are already built, unchanged subtrees of any size cost
O(1)(one 64-char string comparison). Only folders that are ancestors of themchanged files have differing hashes—at mostO(m * D)folders—sodiffinspects only those folders' child lists, plusO(m log m)to sort themoutput entries. In the worst case where every file changed, every node is visited once. - Space:
O(F + folders)nodes in memory, each storing a 64-character hex digest and child pointers, plusO(D)call-stack frames during recursion. On disk, files are read one at a time so peak buffer memory is one file's size.
Edge cases
- Empty or identical repositories: Two empty snapshots
{}share the empty-directory root hash and return[]immediately; two identical 10,000-file snapshots also stop at the root inO(1)diff time. - Empty files (
""): An empty file still gets a valid leaf hash (SHA256(b"file\0")) and is tracked normally asADDED,REMOVED, orMODIFIED. - Renamed files with identical content: Moving
"draft.txt"to"final.txt"keeps the same leaf hash, yet because parent directory hashes include child names, the root hash changes and reports["draft.txt", "REMOVED"]and["final.txt", "ADDED"]. - Sibling files swapping contents: If
"d/a.txt"("1") and"d/b.txt"("2") trade contents, the multiset of leaf hashes inside"d"stays the same, but pairing each hash with its sorted filename changes"d"'s hash and reports both asMODIFIED. - File <-> directory type swaps: Replacing file
"config"with folder"config/db.ini"hitsold.is_file != new.is_file, emitting["config", "REMOVED"]and["config/db.ini", "ADDED"]without ever reporting folders themselves. - Full-path ASCII sort order:
"a.txt"sorts before"a/b"because'.'(ASCII 46) is smaller than'/'(ASCII 47), which differs from tree traversal order where child"a"precedes"a.txt". - On-disk hazards:
.gitis skipped; symbolic links (filesystem pointer files storing a target path rather than regular file data) are hashed as leaves viab"link\0" + targetwithout following cycles; and domain separation (distinct byte prefixesb"file\0",b"link\0",b"dir\0") ensures no two node types can ever collide on hash input.
Common mistakes
- Hashing directory children in
os.listdir()order: Filesystem directory order varies across machines and OSes, causing identical repositories to produce different Merkle hashes. Always sort child names first. - Omitting child names from directory hashes (or sorting children by hash instead of name): Causes renames of identical files (Example 2!) or content swaps between sibling files to produce the exact same folder hash and silently disappear from the diff.
- Concatenating names and hashes without structured escaping: Joining strings naively like
name + hashallows"ab" + ...and"a" + "b..."ambiguity when names contain delimiters; serializing[kind, name, child_hash]triples withjson.dumpsmakes parsing boundaries unambiguous. - Iterating only over
old.childrenduring diff: Misses every newly added file or folder present only innew.children; always iterate overset(old.children) | set(new.children). - Assuming sorted child traversal produces sorted full paths: Visiting child
"a"(folder containing"a/b") before sibling"a.txt"outputs"a/b"before"a.txt", violating full-string sort order unless you sort the final result list. - Opening disk files in text mode (
"r") or following symlinks: Text mode mangles\r\nline endings and crashes withUnicodeDecodeErroron images/binaries, while following directory symlinks can loop infinitely.
Alternative approaches
- Flat hash-map diff: When both snapshots already sit in memory as
{path: content}dictionaries and will only be compared once, scanning keys directly computes the exact same diff inO(B + L + m log m)without building tree nodes. The Merkle tree pays off when trees persist in memory across edits or when hashes are compared across processes/networks. - Content-addressable object store (Git's model): Git stores every file as a
blobobject ("blob <size>\0" + bytes) and every folder as atreeobject listing(mode, name, sha)entries, deduplicating identical subtrees across thousands of historical commits sogit diff commit1 commit2skips shared subtrees instantly.
Follow-up questions
- How could you detect moved or renamed files as RENAMED rather than reporting separate REMOVED and ADDED entries? Because
file_hashdepends only on file bytes and not on the filename, an exact move produces oneREMOVEDentry and oneADDEDentry with the identical leaf hash. In a post-processing pass over themdiff entries, groupREMOVEDpaths by their leaf hash in a dictionary and pair anyADDEDpath sharing that hash asRENAMED(old_path -> new_path)inO(m)extra time; to also catch renames accompanied by small edits (like Git'sgit diff -M), compute chunk/line similarity scores between remaining unmatched removed and added files. - How would two machines synchronize a large codebase over a slow network link using these directory Merkle hashes? First compare root hashes in 1 tiny message—if equal, zero files changed! Otherwise, descend level by level (or batch multiple levels per round trip) requesting child
[kind, name, hash]lists only for directories whose hashes disagree, downloading file contents only forADDEDorMODIFIEDleaves at the bottom, which reduces network traffic fromO(F)hashes toO(m * D * branching_factor). - How would you maintain the Merkle tree incrementally in a code editor as files are edited on disk? Subscribe to OS filesystem watcher events (
FSEventson macOS,inotifyon Linux) so when"a/b/c.py"changes, you rehash just that one file (streaming chunks throughhashlib.sha256().update()for large files) and recompute only theO(D)ancestor directory hashes up toroot. On cold startups, persist an index file caching(mtime_ns, byte_size, leaf_hash)per path (just like.git/index) so unchanged files do not need their contents re-read from disk, and filter out build artifacts using.gitignorerules.
Follow-up questions
- How could you detect moved or renamed files as RENAMED rather than reporting separate REMOVED and ADDED entries?
- How would two machines synchronize a large codebase over a slow network link using these directory Merkle hashes?
- How would you maintain the Merkle tree incrementally in a code editor as files are edited on disk?
Similar questions
- Directory Snapshot Merkle Tree with Path Hashing and Subtree Diffing
- Incremental Markdown Fenced Code Block Parser
- Linking Career Turning Points to an Architectural Deep Dive
- Fault-Tolerant Recurring Job Scheduler
- Design a Hierarchical Sliding-Window Notification Rate Limiter
- Distributed Multi-Scope IDE Configuration Sync
More Cursor interview questions
- Directory Snapshot Merkle Tree with Path Hashing and Subtree Diffing Medium
- Incremental Markdown Fenced Code Block Parser Hard
- Linking Career Turning Points to an Architectural Deep Dive Medium Pro
- Design a Hierarchical Sliding-Window Notification Rate Limiter Medium Pro
- Distributed Multi-Scope IDE Configuration Sync Medium Pro
- Fault-Tolerant Recurring Job Scheduler Medium Pro
- Repository Merkle Hashing and Incremental Tree Diff Medium Pro
- Incremental Merkle Hashing for Virtual Directories Medium Pro
- Subtree-Pruned Workspace Diffing with Merkle Trees Medium Pro
- Binary Merkle Tree Construction and Inclusion Proofs Medium Pro