KatInterview

Finding Identical Files in a Huge Directory Tree

System DesignModel answer
MediumModel answerSystem Designdeduplicationhashingexternal-memory

Last updated

Group byte-identical files across a directory tree too large for memory, minimizing disk reads, staying correct under hash collisions, and scaling out across workers.

You need to find duplicate files in a very large directory tree, where "duplicate" means the files have exactly the same bytes.

You have two primitives:

  • An iterator that yields (path, size) for every file in the tree.
  • A function read_chunks(path) that returns an iterator of bytes pieces for that file. Chunk sizes may be irregular.

Requirements

  1. Keep disk reads to a minimum. Use cheap signals such as file size, and hashes (cryptographic or rolling), to avoid reading files that cannot be duplicates.
  2. Be safe against hash collisions. The output must never contain two files that differ.
  3. Support datasets whose metadata and contents do not fit in memory.
  4. Output groups of paths, where each group contains files that are byte-for-byte identical.

What to cover in your answer

  • The overall algorithm and why it is correct.
  • Time, space and I/O trade-offs.
  • How you would parallelize or distribute the work.
  • Edge cases you would handle.
  • Working code for the core logic.

Hints

Hint 1

Think of a pipeline of filters ordered from cheapest to most expensive. Which property needs no file reads at all, and what can you conclude about a file whose value for that property is unique?

Hint 2

A hash can prove two files differ, but equal hashes only suggest they match. What final step makes the output correct even if a collision occurs, and how can you do it without loading whole files into memory?

Hint 3

For the memory limit, the big structure is the index from size to paths. Consider spilling records to disk partitions keyed by a hash of the size, so each partition can be processed independently. That same independence is what you can parallelize.