KatInterview

Scalable Duplicate File Detection in a Large Directory Tree

System DesignModel answer
MediumModel answerSystem Designhashingfile-systemsdeduplication

Last updated

Design and implement an algorithm to find (and safely remove) duplicate files in a directory tree that may exceed available memory.

The Problem

You have a directory tree that could be arbitrarily large — large enough that you cannot load all file contents, or even all file metadata, into memory at once. Your task is to find every group of files that are byte-for-byte identical, and optionally remove the redundant copies.

Walk through your complete algorithm design. Your answer should cover:

  • Filtering strategy — how you progressively narrow candidates without reading more data than necessary
  • Hashing choices — which hash function(s), why, and how you handle very large files
  • Collision handling — what happens if two files produce the same hash but are not actually identical
  • Memory and I/O efficiency — how you keep both under control at scale
  • Incremental and resumable operation — how a second run avoids redundant work, and how a crash mid-run doesn't require starting over
  • Complexity analysis — time and space, in terms of file count and total bytes
  • Edge cases — hard links, symlinks, empty files, files modified during the scan, permission errors, and anything else worth calling out

You do not need to produce production-ready code, but a working implementation in a language of your choice is a strong addition.

Hints

Hint 1

Start by asking: what's the cheapest property that can rule out two files being identical? Build your algorithm as a sequence of increasingly expensive filters, so you do as little I/O as possible.

Hint 2

Memory is the constraint, so think about where state lives. If Python dicts won't scale, what persistent structure lets you group files by size or hash without loading everything at once — and also gives you resumability for free?

Hint 3

Before you delete anything, consider what could go wrong between the moment you computed a hash and the moment you issue the delete. How do you make the removal step safe?