KatInterview

Hash-Tree Diff: Detect File Changes Between Two Snapshots

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designhashingtrees-graphsrecursion

Last 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:

  1. If both nodes have the same hash, their subtrees are identical — stop immediately and do not inspect children.
  2. If both are files with different hashes, record the path as modified.
  3. 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.
  4. 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.