Skip to content

< all problems109 · Level 04, Tool Calling

Diff Two Directory Trees Into the Fewest Edits

medium · implement · Agents

An agent changed a checkout, and you want the smallest set of edits that turns the old tree into the new one, with moves recognised as moves. Each tree is {path: content}. Implement tree_diff(before, after) and apply_ops(before, ops).

tree_diff returns a list of ops, each a dict:

  • {"op": "rename", "from": p, "to": q}: p is gone and q is new with byte-identical content.
  • {"op": "modify", "path": p, "content": c}: p is in both, with different content c in after.
  • {"op": "add", "path": p, "content": c}: p is only in after.
  • {"op": "delete", "path": p}: p is only in before.
  1. Order. Renames first, then modifies, then adds, then deletes. Within a group, sort by path, and renames by from.
  2. Pairing. A vanished path becomes a rename when a new path has identical content. When several new paths share that content, pair with the one whose path is closest (difflib.SequenceMatcher ratio on the two paths), and on a tie the smaller new path. Each new path pairs once.
  3. Unchanged paths produce no op.
  4. Content wins over name. A path that moved and whose content also changed is a delete and an add, never a rename, because the content is not identical.

apply_ops(before, ops) applies the ops in order and returns the new tree. apply_ops(before, tree_diff(before, after)) must equal after.

The catch. Pair renames before you call anything a plain add or delete, or a moved file shows up as both.