Directory Snapshot Merkle Tree with Path Hashing and Subtree Diffing

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement an N-ary filesystem MerkleTree (using Node objects) that summarizes an on-disk directory hierarchy with deterministic SHA-256 digests, looks up stored digests by relative path, and computes structural diffs between two snapshots while skipping unchanged subtrees.

class Node:
    def __init__(self, name: str, kind: str, hash_hex: str, children: Optional[Dict[str, "Node"]] = None): ...

class MerkleTree:
    def build(self, path: str) -> Node: ...
    def get_hash(self, path: str, tree: Node) -> str: ...
    def diff(self, tree_a: Node, tree_b: Node) -> List[Tuple[str, str]]: ...

Node & Hashing Specification

Each Node stores name (entry basename), kind ("file", "dir", or "link"), hash (64-character lowercase hexadecimal SHA-256 digest), and children (Dict[str, Node], empty {} for "file" and "link" leaves).

  • build(path):

    • If path is empty ("") or missing on disk, raise FileNotFoundError; if path exists as a non-directory, raise NotADirectoryError.
    • If path itself is a symbolic link to a directory, resolve that root link and build the target directory.
    • Inside the directory tree:
      • Regular file ("file"): Stream raw file bytes in chunks and compute sha256(b"file\0" + content_bytes).
      • Symbolic link ("link"): Do not follow internal symlinks; compute sha256(b"link\0" + os.fsencode(os.readlink(entry_path))).
      • Directory ("dir"): Compute sha256(b"dir\0" + records) over all valid children sorted by child name, where each child record is os.fsencode(name) + b"\0" + child.hash.encode("ascii"). An empty directory hashes b"dir\0".
      • Special entries: Skip UNIX sockets, named pipes (FIFOs), and device files.
  • get_hash(path, tree):

    • Return the stored 64-character hex digest for path relative to tree's root without accessing disk.
    • Both "" and "." denote the root node itself; normalize / and OS path separators while ignoring empty segments and "." (so "./app//server.py" resolves to "app/server.py").
    • Raise KeyError if path is missing from tree or attempts to traverse beneath a "file" or "link" leaf.
  • diff(tree_a, tree_b):

    • Compare tree_a (before) against tree_b (after), immediately pruning any pair of nodes whose hash values are equal without inspecting their children.
    • Return (change, relative_path) tuples ordered depth-first with sibling names visited in sorted order (/-separated paths relative to the root), where change is:
      • "added": entry exists only in tree_b (an added directory is reported once by its own path, not file by file).
      • "removed": entry exists only in tree_a (a removed directory is reported once by its own path).
      • "modified": entry exists in both trees and either both are leaves with different hashes ("file" or "link"), or the entry's kind changed (for example, "file" replaced by "dir"). Directories present as "dir" in both trees that differ only because descendants changed are recursed into rather than listed themselves.

Examples

Example 1

Input:

Snapshot 1 (d1):
  app/config/prod.json -> "port=8080"
  app/server.py        -> "run()"
  vendor/lib.py        -> "v1"
  logs/                -> (empty directory)

Snapshot 2 (d2):
  Same as d1, except app/config/prod.json -> "port=9090"

Output:

mt.get_hash("logs", t1)                 -> "34312174686ce443db57c7fda1233d8a4615dd0ac30168116fcf35fee068e0ba"
mt.get_hash("app/config/prod.json", t1) -> "0c5a856602c65b984327ff482f41b39fbd6ff0710722d4612a28c5a7432b4126"
mt.diff(t1, t2)                         -> [("modified", "app/config/prod.json")]

Walk-through: Editing app/config/prod.json changes the hash of app/config/prod.json, app/config, app, and the root "", while "app/server.py", "vendor", and "logs" keep identical hashes. During diff(t1, t2), "vendor" and "logs" are skipped in O(1) because their hashes match, and recursion follows "app" -> "app/config" -> "app/config/prod.json".

Example 2

Input:

Snapshot A (dir_a):
  README.md   -> "intro"
  legacy.txt  -> "old"
  cache       -> "flat"          (regular file)
  pkg/util.py -> "v1"

Snapshot B (dir_b):
  README.md             -> "intro"
  assets/logo.svg       -> "<svg/>"
  assets/icons/home.svg -> "<path/>"
  cache/index.db        -> "rows"  (directory replacing file)
  pkg/util.py           -> "v2"
  pkg/extra.py          -> "new"

Output:

mt.diff(tree_a, tree_b) -> [
  ("added", "assets"),
  ("modified", "cache"),
  ("removed", "legacy.txt"),
  ("added", "pkg/extra.py"),
  ("modified", "pkg/util.py")
]

Walk-through: "README.md" has identical hashes and is skipped. The new "assets" directory is reported as a single "added" entry without expanding its files. "cache" swapped kind from "file" to "dir", producing one "modified" entry. "legacy.txt" was deleted ("removed"), and "pkg" differs on both sides as "dir", so diff recurses into its sorted children "extra.py" and "util.py".

Constraints

  • Use the Python standard library only (hashlib, os, typing).
  • Stream file contents in fixed-size chunks during build so memory usage does not scale with individual file size.
  • get_hash(path, tree) must run in O(depth) time using only the in-memory Node tree, and diff(tree_a, tree_b) must never inspect node.children when two compared nodes already have equal hashes.

Step-by-step walkthrough

  1. Clarify the open design choices up front

    Because the problem lets us choose the tree representation and reporting contract, state clean, git-style rules at the beginning and record them in the docstrings:

    • Lookup paths (get_hash): Relative to the root directory using / separators ("" and "." refer to the root itself). Any path not in the tree raises KeyError.
    • Hash function: 64-character lowercase hexadecimal SHA-256 strings.
    • What affects a hash: File bytes, symlink target strings, entry kinds ("file", "dir", "link"), and child names inside their parent directory. Permissions and modification times are ignored; renaming a file keeps the file's own hash unchanged while changing its parent directory's hash (and every ancestor above it).
    • Special entries: Empty directories are valid "dir" nodes. Symlinks inside the tree are "link" leaves hashed from os.readlink and never followed (preventing link cycles). If the root path passed to build(path) is itself a symlink to a directory (like /tmp on macOS), we resolve that root so we build the directory. Sockets, FIFOs, and device nodes are skipped; unreadable files raise OSError rather than silently producing an incomplete tree.
    • diff(tree_a, tree_b) output: Returns (change, relative_path) pairs in depth-first name order, where change is "added", "removed", or "modified". Added or removed directories are reported once (not expanded file by file); "modified" covers edited files/links and type replacements ("file" <-> "dir").
  2. Design deterministic, collision-safe hashes

    A Merkle tree's correctness hinges on one guarantee: two nodes have the same hash if and only if their subtrees have the exact same structure and contents (barring an astronomical SHA-256 collision). Two simple rules enforce that guarantee:

    1. Sort child names before hashing: os.listdir returns entries in filesystem-dependent order. Sorting child names ensures identical folders always feed identical byte sequences into SHA-256 on every OS.
    2. Make byte encodings unambiguous (domain tags + NUL delimiters):
      • Prefix every hash input with its entry kind (b"file\0", b"link\0", b"dir\0"). Without those tags, an empty file and an empty directory would both hash b"" and share the exact same digest!
      • Separate each child's name from its 64-character hex hash with b"\0". Without a separator, concatenating name + hash directly lets two children {"a": H1, "b": H2} ("a" + H1 + "b" + H2) produce the exact same bytes as one bizarrely named child {"a" + H1 + "b": H2}. Because filenames on POSIX and Windows can never contain a NUL byte (b"\0"), and every SHA-256 hex digest is fixed at 64 ASCII characters, there is only one way to parse the bytes back into (name, hash) pairs:
    Leaf file:   sha256( b"file\0" + <raw file bytes> )
    Leaf link:   sha256( b"link\0" + <raw symlink target bytes> )
    Directory:   sha256( b"dir\0"  + name_1 + b"\0" + hash_1 (64 chars)
                                   + name_2 + b"\0" + hash_2 (64 chars) + ... )   [names sorted]
    
  3. Define the Node class and streaming leaf hashes

    Each Node stores its name, kind ("file", "dir", or "link"), hash, and a children dictionary mapping child_name -> child_Node (empty {} for leaves). Using a dictionary for children gives O(1) step-by-step lookups in get_hash and clean name matching in diff.

    To hash arbitrarily large files safely, hash_file feeds hashlib.sha256() 64 KiB chunks in a loop — producing the exact same digest as reading the whole file at once while keeping memory usage constant at 64 KiB:

    from typing import Dict, List, Optional, Tuple
    import hashlib
    import os
    
    CHUNK_SIZE = 1 << 16  # 64 KiB
    
    
    class Node:
        def __init__(self, name: str, kind: str, hash_hex: str, children: Optional[Dict[str, "Node"]] = None):
            self.name = name
            self.kind = kind
            self.hash = hash_hex
            self.children = children if children is not None else {}
    
    
    def hash_file(full_path: str) -> str:
        """Compute sha256(b'file\\0' + raw_bytes) by streaming fixed-size chunks from disk."""
        hasher = hashlib.sha256()
        hasher.update(b"file\0")
        with open(full_path, "rb") as file_obj:
            while True:
                chunk = file_obj.read(CHUNK_SIZE)
                if not chunk:
                    break
                hasher.update(chunk)
        return hasher.hexdigest()
    
    
    def hash_link(full_path: str) -> str:
        """Compute sha256(b'link\\0' + raw_target_bytes) without following the symlink."""
        hasher = hashlib.sha256()
        hasher.update(b"link\0")
        target_bytes = os.fsencode(os.readlink(full_path))
        hasher.update(target_bytes)
        return hasher.hexdigest()
    
  4. Build the tree bottom-up with post-order recursion

    A parent directory cannot compute hash_dir(children) until all of its children already have their hashes, so build_node performs a post-order traversal (build children first, then hash the parent).

    Pay close attention to the order of type checks:

    • Check os.path.islink first inside build_node: both os.path.isdir and os.path.isfile follow symlinks, so checking isdir first would walk into symlinked directories and loop forever on loop -> ...
    • Resolve the root path once in MerkleTree.build via os.path.realpath(path): on macOS, tempfile.TemporaryDirectory() lives under /var or /tmp (both symlinks into /private/...), and a caller passing a symlinked root directory wants its contents built, not a single "link" leaf.
    def hash_dir(children: Dict[str, Node]) -> str:
        hasher = hashlib.sha256()
        hasher.update(b"dir\0")
        for name in sorted(children):
            hasher.update(os.fsencode(name))
            hasher.update(b"\0")
            hasher.update(children[name].hash.encode("ascii"))
        return hasher.hexdigest()
    
    
    def build_node(full_path: str, name: str) -> Optional[Node]:
        if os.path.islink(full_path):
            return Node(name, "link", hash_link(full_path))
    
        if os.path.isdir(full_path):
            children: Dict[str, Node] = {}
            for entry_name in os.listdir(full_path):
                child_path = os.path.join(full_path, entry_name)
                child_node = build_node(child_path, entry_name)
                if child_node is not None:
                    children[entry_name] = child_node
            return Node(name, "dir", hash_dir(children), children)
    
        if os.path.isfile(full_path):
            return Node(name, "file", hash_file(full_path))
    
        return None
    
  5. Implement O(depth) hash lookup by walking the tree

    Once build returns the root Node, every hash is already stored in memory — get_hash never touches the disk. We normalize separators, ignore empty segments and "." (so "", ".", and "./a//b.txt" all work cleanly), and step through node.children one segment at a time. Notice that if someone asks for "a/b.txt/c", b.txt is a file with children == {}, so "c" not in node.children naturally raises KeyError:

    def split_path(path: str) -> List[str]:
        parts: List[str] = []
        normalized = path.replace(os.sep, "/")
        for part in normalized.split("/"):
            if part not in ("", "."):
                parts.append(part)
        return parts
    
    
    def get_hash(self, path: str, tree: Node) -> str:
        node = tree
        for part in split_path(path):
            if part not in node.children:
                raise KeyError(path)
            node = node.children[part]
        return node.hash
    
  6. Diff two trees by pruning identical hashes

    Here is where the Merkle tree pays off: at the top of _diff_dirs(a, b, prefix, changes), if a.hash == b.hash, we return immediately without looking at a single child inside a or b. Even if a subdirectory holds 100,000 unchanged files, one string comparison skips all of them in O(1) time.

    When a.hash != b.hash, we iterate over sorted(set(a.children) | set(b.children)) so results always come out in deterministic order:

    • Missing from a -> ("added", rel_path) (reports a newly added folder once without expanding it).
    • Missing from b -> ("removed", rel_path) (reports a deleted folder once).
    • child_a.hash == child_b.hash -> continue (unchanged file, link, or whole subfolder).
    • Both are "dir" -> recurse into _diff_dirs(child_a, child_b, rel_path, changes).
    • Otherwise (file/link content changed, or entry kind swapped between "file", "dir", and "link") -> ("modified", rel_path).
    def join_path(prefix: str, name: str) -> str:
        if prefix:
            return f"{prefix}/{name}"
        return name
    
    
    class MerkleTree:
        # ... build and get_hash ...
    
        def diff(self, tree_a: Node, tree_b: Node) -> List[Tuple[str, str]]:
            changes: List[Tuple[str, str]] = []
            self._diff_dirs(tree_a, tree_b, "", changes)
            return changes
    
        def _diff_dirs(self, a: Node, b: Node, prefix: str, changes: List[Tuple[str, str]]) -> None:
            if a.hash == b.hash:
                return
    
            all_names = sorted(set(a.children) | set(b.children))
            for name in all_names:
                rel_path = join_path(prefix, name)
                child_a = a.children.get(name)
                child_b = b.children.get(name)
    
                if child_a is None:
                    changes.append(("added", rel_path))
                elif child_b is None:
                    changes.append(("removed", rel_path))
                elif child_a.hash == child_b.hash:
                    continue
                elif child_a.kind == "dir" and child_b.kind == "dir":
                    self._diff_dirs(child_a, child_b, rel_path, changes)
                else:
                    changes.append(("modified", rel_path))
    
  7. Write self-cleaning disk tests

    To verify all three methods against real on-disk directories cleanly, wrap every test in with tempfile.TemporaryDirectory() as tmp: so temporary folders are deleted automatically even if an assert fails. Three high-signal checks catch subtle bugs fast:

    1. Ancestor-only hash propagation: Edit one deep file (app/config/prod.json) and assert that "", "app", "app/config", and "app/config/prod.json" all changed hash while sibling "app/server.py" and cousin "vendor" kept the exact same hash.
    2. Hand-computed SHA-256 check: On modern filesystems (APFS, ext4), creating files in different orders often still lists them in the same internal B-tree/hash order, letting unsorted code pass accidentally. Asserting get_hash("sub", tree) == expected_sha256 computed directly from sorted names ["a", ..., "f"] proves sorting works.
    3. Subtree-pruning proof: Set t1.children["vendor"].children = None and t2.children["vendor"].children = None on an unchanged directory before calling mt.diff(t1, t2) — if diff tried to peek inside "vendor", it would crash with TypeError!
    import os
    import tempfile
    
    
    def _write_file(root: str, rel_path: str, text: str) -> None:
        full = os.path.join(root, *rel_path.split("/"))
        os.makedirs(os.path.dirname(full), exist_ok=True)
        with open(full, "wb") as f:
            f.write(text.encode("utf-8"))
    
    
    def demo_single_edit_test() -> None:
        with tempfile.TemporaryDirectory() as d:
            _write_file(d, "app/config/prod.json", "port=8080")
            _write_file(d, "app/server.py", "run()")
            _write_file(d, "vendor/lib.py", "v1")
            mt = MerkleTree()
            before = mt.build(d)
    
            _write_file(d, "app/config/prod.json", "port=9090")
            after = mt.build(d)
    
            for ancestor in ("app/config/prod.json", "app/config", "app", ""):
                assert mt.get_hash(ancestor, before) != mt.get_hash(ancestor, after)
            for untouched in ("app/server.py", "vendor", "vendor/lib.py"):
                assert mt.get_hash(untouched, before) == mt.get_hash(untouched, after)
            assert mt.diff(before, after) == [("modified", "app/config/prod.json")]
    
  8. Trace one file edit through build and diff

    Suppose a directory contains app/config/prod.json = "port=8080", app/server.py = "run()", and a large vendor/ subtree with 10,000 unchanged files. Then app/config/prod.json is edited to "port=9090":

    Before -> After hashes:
      app/config/prod.json:  0c5a8566... -> 6b17c238...   (CHANGED: leaf bytes changed)
      app/config:            changed                      (CHANGED: child prod.json hash changed)
      app/server.py:         same                         (unchanged leaf)
      app:                   changed                      (CHANGED: child config hash changed)
      vendor/:               same                         (unchanged subtree of 10,000 files!)
      root (""):             changed                      (CHANGED: child app hash changed)
    
    Walk of diff(before, after):
      1. root hashes differ           -> inspect children ["app", "vendor"]
      2.   "app": both "dir", differ  -> recurse into "app", inspect ["config", "server.py"]
      3.     "config": "dir", differ  -> recurse into "app/config", inspect ["prod.json"]
      4.       "prod.json": file diff -> append ("modified", "app/config/prod.json")
      5.     "server.py": equal hash  -> skip!
      6.   "vendor": hashes equal     -> PRUNE! All 10,000 files under vendor/ skipped in O(1)!
    
  9. Complete solution

    from typing import Dict, List, Optional, Tuple
    import hashlib
    import os
    
    # Stream files 64 KiB at a time so multi-gigabyte files never sit in RAM at once.
    CHUNK_SIZE = 1 << 16
    
    
    class Node:
        """One entry of the tree.
    
        kind is "file", "dir" or "link"; hash is a hex SHA-256 string;
        children maps a child's name to its Node (always empty for files and links).
        """
    
        def __init__(self, name: str, kind: str, hash_hex: str, children: Optional[Dict[str, "Node"]] = None):
            self.name = name
            self.kind = kind
            self.hash = hash_hex
            # children: {entry_name: Node} for directories; empty dict {} for file and link leaves.
            self.children = children if children is not None else {}
    
    
    def hash_file(full_path: str) -> str:
        """Compute sha256(b'file\\0' + raw_bytes) by streaming fixed-size chunks from disk."""
        hasher = hashlib.sha256()
        # Prefix with a domain tag so an empty file never collides with an empty directory.
        hasher.update(b"file\0")
        with open(full_path, "rb") as file_obj:
            while True:
                chunk = file_obj.read(CHUNK_SIZE)
                if not chunk:
                    break
                hasher.update(chunk)
        return hasher.hexdigest()
    
    
    def hash_link(full_path: str) -> str:
        """Compute sha256(b'link\\0' + raw_target_bytes) without following the symlink."""
        hasher = hashlib.sha256()
        hasher.update(b"link\0")
        target_bytes = os.fsencode(os.readlink(full_path))
        hasher.update(target_bytes)
        return hasher.hexdigest()
    
    
    def hash_dir(children: Dict[str, Node]) -> str:
        """Compute sha256(b'dir\\0' + sorted child records) so listing order never affects the hash."""
        hasher = hashlib.sha256()
        hasher.update(b"dir\0")
        # Sort child names so two directories with identical contents always produce the same digest.
        for name in sorted(children):
            # Because POSIX/Windows filenames cannot contain b"\0" and SHA-256 hex is always
            # 64 ASCII bytes, name + b"\0" + hex_hash can be parsed back in only one way.
            hasher.update(os.fsencode(name))
            hasher.update(b"\0")
            hasher.update(children[name].hash.encode("ascii"))
        return hasher.hexdigest()
    
    
    def build_node(full_path: str, name: str) -> Optional[Node]:
        """Recursively build a Node bottom-up; return None for special files like sockets or FIFOs."""
        # Check islink() BEFORE isdir()/isfile() because both isdir() and isfile() follow symlinks
        # and would recurse into symlinked directories (risking infinite loops on link cycles).
        if os.path.islink(full_path):
            return Node(name, "link", hash_link(full_path))
    
        if os.path.isdir(full_path):
            children: Dict[str, Node] = {}
            for entry_name in os.listdir(full_path):
                child_path = os.path.join(full_path, entry_name)
                child_node = build_node(child_path, entry_name)
                if child_node is not None:
                    children[entry_name] = child_node
            return Node(name, "dir", hash_dir(children), children)
    
        if os.path.isfile(full_path):
            return Node(name, "file", hash_file(full_path))
    
        # Skip non-regular entries (UNIX domain sockets, named pipes/FIFOs, device nodes).
        return None
    
    
    def split_path(path: str) -> List[str]:
        """Split a relative path into clean components, ignoring empty segments and '.'."""
        parts: List[str] = []
        normalized = path.replace(os.sep, "/")
        for part in normalized.split("/"):
            if part not in ("", "."):
                parts.append(part)
        return parts
    
    
    def join_path(prefix: str, name: str) -> str:
        """Join a relative directory prefix and child name with '/'."""
        if prefix:
            return f"{prefix}/{name}"
        return name
    
    
    class MerkleTree:
        def build(self, path: str) -> Node:
            """Build the tree for the directory at `path` and return its root Node.
    
            File hash:      sha256(b"file\\0" + content), content read in chunks.
            Link hash:      sha256(b"link\\0" + link target); links are not followed.
            Directory hash: sha256(b"dir\\0" + for each child in name order:
                                   name (UTF-8) + b"\\0" + child hash (64 hex chars)).
            Other special files (sockets, FIFOs, devices) are skipped.
            If `path` itself is a link to a directory, the directory is built.
            """
            if not path or not os.path.exists(path):
                raise FileNotFoundError(path)
            if not os.path.isdir(path):
                raise NotADirectoryError(path)
    
            # Resolve symlinks on the root path itself (e.g. /tmp -> /private/tmp on macOS)
            # so build_node constructs the directory tree rather than a single "link" leaf.
            resolved_root = os.path.realpath(path)
            return build_node(resolved_root, os.path.basename(resolved_root))
    
        def get_hash(self, path: str, tree: Node) -> str:
            """Hash of the entry at `path`, relative to the tree's root ("" or "." is the root).
    
            Raise KeyError if the path is not in the tree.
            """
            node = tree
            for part in split_path(path):
                # File and link nodes have children == {}, so paths stepping through a file
                # (like "a/b.txt/c") also fail this check and raise KeyError.
                if part not in node.children:
                    raise KeyError(path)
                node = node.children[part]
            return node.hash
    
        def diff(self, tree_a: Node, tree_b: Node) -> List[Tuple[str, str]]:
            """List of (change, path) with change in "added", "removed", "modified".
    
            An added or removed directory is reported once, not file by file.
            "modified" is reported for files and links whose hash differs and for paths
            whose kind changed (file <-> dir); directories that merely contain changes
            are not listed themselves. Order: depth-first, children in name order.
            """
            # changes: list of ("added" | "removed" | "modified", relative_path) tuples
            changes: List[Tuple[str, str]] = []
            self._diff_dirs(tree_a, tree_b, "", changes)
            return changes
    
        def _diff_dirs(self, a: Node, b: Node, prefix: str, changes: List[Tuple[str, str]]) -> None:
            """Compare two directory nodes, pruning any subtree whose SHA-256 hash matches."""
            if a.hash == b.hash:
                # Equal Merkle hashes guarantee identical contents all the way down; skip subtree.
                return
    
            all_names = sorted(set(a.children) | set(b.children))
            for name in all_names:
                rel_path = join_path(prefix, name)
                child_a = a.children.get(name)
                child_b = b.children.get(name)
    
                if child_a is None:
                    # Present only in tree_b (whole added directory is reported once).
                    changes.append(("added", rel_path))
                elif child_b is None:
                    # Present only in tree_a (whole removed directory is reported once).
                    changes.append(("removed", rel_path))
                elif child_a.hash == child_b.hash:
                    # Unchanged file, link, or entire subdirectory: prune immediately.
                    continue
                elif child_a.kind == "dir" and child_b.kind == "dir":
                    # Both sides are directories whose contents differ: recurse without listing rel_path itself.
                    self._diff_dirs(child_a, child_b, rel_path, changes)
                else:
                    # Edited file/link content, or a kind swap such as file <-> dir.
                    changes.append(("modified", rel_path))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine comparing yesterday's and today's snapshots of a huge library without flipping through every book: if each shelf carries a tamper-evident seal computed from the seals of the books on it, and each room carries a seal computed from its shelves, two matching room seals immediately prove every book inside that room is untouched. A Merkle tree is a tree data structure where every leaf stores a cryptographic hash (a fixed-size 64-character SHA-256 fingerprint where altering a single byte completely changes the output) of a file's contents, and every internal directory node stores the hash of its sorted (child_name, child_hash) entries. When two directory nodes have equal hashes, diff skips their entire subtrees in a single O(1) string comparison; when they differ, diff drills down only into the specific branches whose hashes changed.

Why does a naive file-by-file comparison or careless hashing fail? Walking every path in two flat snapshots of 500,000 files takes O(E) work even when zero or one file changed. Meanwhile, hashing os.listdir entries without sorting makes identical folders produce different hashes on different filesystems, omitting domain separation (distinct prefixes like b"file\0" vs b"dir\0" for each node type) gives an empty file and an empty folder the exact same hash, and concatenating name + child_hash without a b"\0" delimiter allows two different child layouts to serialize into identical bytes.

Let's trace our sample directory with app/config/prod.json = "port=8080", app/server.py = "run()", vendor/lib.py = "v1", and empty logs/, after editing app/config/prod.json to "port=9090":

1. Bottom-up build:
   hash("app/config/prod.json") = sha256(b"file\0port=9090")                       <- changed!
   hash("app/config")           = sha256(b"dir\0prod.json\0" + H_prod)             <- changed!
   hash("app")                  = sha256(b"dir\0config\0" + H_cfg + b"server.py\0" + H_srv) <- changed!
   hash("logs")                 = sha256(b"dir\0")                                 <- UNCHANGED!
   hash("vendor")               = sha256(b"dir\0lib.py\0" + H_lib)                 <- UNCHANGED!
   hash("")                     = sha256(b"dir\0app\0" + H_app + b"logs\0" + H_logs + b"vendor\0" + H_ven) <- changed!

2. Top-down diff(t1, t2):
   root hashes differ -> check children ["app", "logs", "vendor"]
     "app" hashes differ (both "dir") -> recurse, check ["config", "server.py"]
       "config" hashes differ (both "dir") -> recurse, check ["prod.json"]
         "prod.json" is a file with different hashes -> record ("modified", "app/config/prod.json")
       "server.py" hashes match -> skip!
     "logs" hashes match   -> PRUNE!
     "vendor" hashes match -> PRUNE entire "vendor" subtree without opening it!

Complexity

Let B be the total bytes across all files, E be the total number of directory entries, c_i be the child count of directory i, and d be the depth (number of path segments) of a path.

  • build(path) — Time: O(B + sum(c_i log c_i)) (at most O(B + E log E)), Space: O(E). We stream all B file bytes through SHA-256 once in fixed 64 KiB chunks (O(1) buffer RAM regardless of file size) and sort each directory's c_i child names in O(c_i log c_i) time; the resulting tree stores one Node per entry (O(E) memory) plus O(max_depth) call-stack frames.
  • get_hash(path, tree) — Time: O(d), Space: O(d). split_path produces at most d path segments, and each step performs one O(1) dictionary lookup in node.children without touching the disk.
  • diff(tree_a, tree_b) — Time: O(sum(c_i log c_i)) over only the directories whose hashes differ, Space: O(K + D_active). Because equal hashes prune unchanged subtrees in O(1), editing one file at depth d = 5 with ~20 entries per folder inspects only 5 directories (~100 entries) even if 1,000,000 unchanged files sit elsewhere; memory holds the K reported changes plus sorted child-name lists along the active recursion path (D_active).

Edge cases

  • Empty directory vs empty file (slot/ vs slot): Domain tags produce sha256(b"dir\0") vs sha256(b"file\0"), so their hashes never collide and diff reports ("modified", "slot").
  • Kind swap ("file" replaced by "dir" at the same path cache): Reported once as ("modified", "cache") without listing every file inside the new directory.
  • Whole added or deleted directory (assets/): Reported once as ("added", "assets") or ("removed", "assets") because _diff_dirs does not expand one-sided subtrees.
  • Renamed file with identical bytes: Because a file's name lives in its parent's hash rather than the leaf's hash, get_hash("dir/before.txt", t1) == get_hash("dir/after.txt", t2), while dir's hash changes and diff reports ("added", "dir/after.txt") and ("removed", "dir/before.txt").
  • Root lookups and redundant slashes: get_hash("", tree) and get_hash(".", tree) return tree.hash, and "./app//server.py" normalizes cleanly to ["app", "server.py"]. Two identical directories at different root paths (/tmp/d1 vs /tmp/d2) have identical root hashes because a directory's own name is hashed by its parent, not itself.
  • Stepping through a file ("app/server.py/sub"): Leaf nodes have children = {}, so "sub" not in node.children raises KeyError.
  • Symlinks inside vs at the root: Internal symlinks are hashed as "link" leaves (os.path.islink runs before isdir) so cycles like loop -> .. never recurse; a symlink passed as build(path)'s root is resolved via os.path.realpath so the target directory is built.
  • Special files and bad roots: Sockets, FIFOs, and devices are skipped (None), while an empty, missing, or non-directory path in build(path) raises FileNotFoundError or NotADirectoryError.

Common mistakes

  • Hashing os.listdir directly without sorting: Produces different directory hashes across runs or operating systems for identical contents.
  • Concatenating name + child_hash with no delimiter: Allows crafted filenames containing hex characters to collide with two separate child entries.
  • Forgetting domain tags (file\0, dir\0, link\0): Causes empty files and empty folders (or a file whose content mimics child records) to hash identically.
  • Reading entire files via f.read(): Exhausts RAM when a directory contains multi-gigabyte media, log, or model-weight files.
  • Checking os.path.isdir before os.path.islink: Follows directory symlinks and crashes with RecursionError on symlink cycles.
  • Walking every node in diff without if a.hash == b.hash: return: Throws away the O(changed branches) speedup that motivated building a Merkle tree in the first place.
  • Relying only on reversed file-creation order to test directory sorting: Modern filesystems like APFS and ext4 return os.listdir in deterministic internal order regardless of creation order; compare against a hand-computed SHA-256 digest to genuinely test sorting.

Alternative approaches

  • Content-addressed object store (hash -> Node, like Git's .git/objects): Deduplicates identical subdirectories and files across dozens of historical snapshots so unchanged subtrees consume zero extra RAM or disk.
  • Include POSIX file mode bits in child records: If executable permissions (0o755 vs 0o644) matter — as in source-code repositories — include the mode before the child name (mode + b" " + name + b"\0" + hash).
  • Explicit stack instead of recursion in build_node: Prevents hitting Python's 1,000-frame recursion limit on pathologically deep (>1,000 nested folders) trees.

Follow-up questions

  • After constructing a snapshot tree, a single file on disk is modified. How can you refresh the tree incrementally instead of rescanning every directory? Step down from the root along the edited file's d path components (O(d) dictionary lookups), stream-hash only that one modified file from disk, and recompute hash_dir for each of the d ancestor folders on the way back up while reusing every sibling's existing hash. For a 10 KB edit at depth 6 with 20 entries per folder, you hash 10 KB plus 6 * 20 = 120 short child records rather than rereading gigabytes of unchanged files. To preserve the prior snapshot for diff(old_tree, new_tree), use path copying (also known as structural sharing, allocating d + 1 fresh Node instances along the root-to-leaf spine while sharing all unchanged sibling references with old_tree).
  • Suppose the two directory snapshots reside on separate servers over a slow network link. How do you locate all changed paths with minimal bandwidth? Turn _diff_dirs into a top-down RPC protocol: Server A sends its 32-byte root digest; if it matches Server B's root digest, synchronization finishes in 0 extra bytes. Whenever a directory hash differs, Server B returns the (name, kind, hash) tuples of that folder's immediate children, and Server A requests expansion only for child folders whose digests differ (batching all differing folders at depth k into a single round trip). For one edited file at depth 5 with 20 entries per directory, only 5 * 20 = 100 child records (~5 KB across 5 round trips) cross the wire instead of 1,000,000 * 32 B = 32 MB of flat file hashes, followed by transferring only modified files (or changed byte ranges via a rolling checksum — a sliding-window hash like rsync uses to pinpoint edited blocks inside a large file).
  • If the root folder contains millions of files, how would you optimize build for high throughput? First, skip rehashing untouched files by persisting a stat cache (path -> (size, mtime_ns, inode, sha256)) across builds — just like Git's .git/index — and reusing the stored digest whenever file size, nanosecond modification timestamp, and inode (the filesystem's unique numeric entry ID) are unchanged. Second, switch from os.listdir + islink/isdir/isfile to os.scandir to eliminate millions of extra stat syscalls, and replace recursion with an explicit stack. Third, hash cold or edited files across a ThreadPoolExecutor: CPython's hashlib releases the Global Interpreter Lock (GIL) (the interpreter lock that serializes Python bytecode across threads) on buffers above 2 KiB, letting disk I/O and SHA-256 (or faster hashlib.blake2b) run concurrently across CPU cores.
  • How could you extend diff to recognize renamed or relocated files instead of emitting separate removal and addition entries? Because hash_file hashes b"file\0" + content without the filename (storing names inside the parent directory record instead), moving or renaming a file leaves its 64-character leaf digest untouched. Run diff first, index every "removed" entry by (kind, node.hash) -> old_path (which also works for relocated directories since hash_dir omits the directory's own name), and pair any "added" entry sharing the same (kind, hash) into ("moved", old_path, new_path), breaking ties among identical copies by path/basename similarity. To catch files that were moved and lightly edited, compare remaining unmatched deletions and additions of similar byte size using content-defined chunk fingerprints (for instance, Git flags a rename when at least 50% of chunks overlap).

Follow-up questions

Similar questions

More Cursor interview questions

All 11 Cursor questions →