Katkat

Implement a Merkle-tree repo diff

CursorSoftware Engineer · Technical Screen

Last updated

This question evaluates a candidate's understanding of Merkle trees, filesystem-aware hashing, directory traversal, and diff algorithms for detecting file-level changes.

You are given two snapshots of a source-code repository on disk, each represented by a root directory path. Implement a Merkle tree over the directory structure (folders are internal nodes, files are leaves), and use it to compute which files changed between the two snapshots.

Use the following API (Python-like):

from enum import Enum, auto
from typing import Self

class ChangeType(Enum):
 ADDED = auto()
 MODIFIED = auto()
 REMOVED = auto()

class MerkleTree:
 def __init__(self, root_directory: str):
 """Build the Merkle tree from the filesystem under root_directory."""
 ...

 def diff(self, other: Self) -> list[tuple[str, ChangeType]]:
 """Return a list of (relative_path, ChangeType) for all files that differ."""
 ...

Requirements / clarifications:

  • The tree structure must follow the actual folder hierarchy in the repo (not a binary tree).
  • A file node’s hash should depend on its contents (and optionally its name); a directory node’s hash should depend on its children (names + hashes) in a deterministic order.
  • diff() should report files only as:
  • ADDED: path exists only in other.
  • REMOVED: path exists only in self.
  • MODIFIED: path exists in both but file contents differ.
  • Paths in the output should be relative to the root (e.g., "src/main.py").
  • If a path changes type (file ↔ directory), you may treat it as removed + added for the affected file paths.
  • Use only the standard library to read directories/files.

Design and implement the data structures and logic so it can run against real repositories on disk.