Scalable Duplicate File Detection in a Large Directory Tree
System DesignModel answerLast 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: a progressive filtering funnel
The core insight is that two files can only be identical if every cheap property matches first. You structure the algorithm as a funnel: apply the least expensive filter first, discard anything that's already unique, and only move on to the next, costlier stage with what remains. This minimises both I/O and memory.
Stage 1 — file size (free).
Call stat on every file. No file content is read at all. In a typical filesystem, the vast majority of files have a unique size and fall out here immediately.
Stage 2 — partial hash. For files that share a size with at least one other file, read the first and last 64 KB and hash those bytes together. This catches the common case of files with identical headers but different payloads (or vice versa), like log files or media containers. Files of 128 KB or less are fully covered by this step, so their partial hash doubles as their full hash.
Stage 3 — full hash. Stream the remaining candidates (those that matched on both size and partial hash) through the hash function in fixed chunks — 1 MB is a reasonable chunk size. Only a small fraction of files reach this stage.
Stage 4 — byte-for-byte comparison before deletion.
Hashing is probabilistic. Before actually removing a file, do a direct byte comparison against the file you intend to keep. Deletion is irreversible, so this final check is non-negotiable. Re-stat the file right before deletion too: if its mtime or size changed since you hashed it, skip it rather than risk deleting something that was modified mid-scan (a classic TOCTOU race).
Hashing strategy
Choice of hash function. BLAKE2b-256 is a good default: it's cryptographically strong and faster than SHA-256. With a 256-bit digest, the probability of an accidental collision across a billion files is around 2⁻¹⁹⁰ — effectively zero. If you're willing to always follow up with a byte compare, a non-cryptographic hash like xxHash is faster still and perfectly safe.
Streaming large files. Never load a whole file into memory. Read in fixed chunks so memory per file is O(chunk size), regardless of file size.
Head-and-tail sampling. The partial hash reads both ends of the file, not just the beginning. Many real formats (ZIP archives, MP4 videos, append-only logs) differ primarily at one end; reading both ends catches more divergence cheaply.
Resumable hashing of very large files. For multi-gigabyte files, a single-pass streaming hash can't resume if it's interrupted. Python's hashlib state isn't serialisable. A practical solution is to hash the file in fixed-size chunks (say 64 MB each), store those per-chunk digests, and combine them into a Merkle-style root. This lets you resume from a checkpoint mid-file and parallelise chunk hashing if needed. Rolling hashes (Rabin fingerprints, FastCDC) are worth mentioning as an extension for block-level or near-duplicate detection, but they're overkill for whole-file equality.
Keeping state on disk: why SQLite
Once the tree is too large for memory, you need somewhere persistent to store paths, sizes, and hashes while grouping them. SQLite works well here:
- Grouping queries (
GROUP BY size HAVING COUNT(*) > 1) run on indexed columns and never require a full in-memory sort. - Caching hashes keyed on
(path, dev, inode, size, mtime_ns)makes reruns incremental: if the file is unchanged, the cached hash is reused. - Committing in batches (every ~1,000 rows) means a crash loses at most one batch of work.
Memory and I/O optimisation
- Walk the tree with an explicit stack rather than recursion, to avoid hitting Python's recursion limit on deep trees.
os.scandirreturns cachedDirEntryobjects that avoid extrastatsyscalls. - Never read file content until the file has survived the size filter; never read full content until it has survived the partial-hash filter.
- On SSDs or network storage, a thread pool speeds up I/O-bound hashing. On spinning disks, sort candidates by inode number before reading to minimise seek thrashing.
- Index the
sizecolumn and the(size, partial_hash)composite column so grouping queries stay fast even with millions of rows.
Complexity
Let N = number of files, S = total bytes, k = files that share a size with another file, S_c = bytes belonging to files that survive to the full-hash stage.
- Time: O(N) for the stat walk, plus O(k · 128 KB) for partial hashes, plus O(S_c) for full hashes, plus up to O(S_c) again for byte-by-byte verification before deletion. Worst case (all files identical) is O(S).
- Space (RAM): O(tree depth + chunk size). State is on disk, not in memory.
- Space (disk): O(N) for the database.
- Incremental rerun: O(N) stat calls, with I/O only for files that are new or changed since the last run.
Edge cases worth calling out
- Hard links. Two paths sharing the same
(dev, inode)pair occupy no extra space. Never count them as duplicates, and never delete a path that shares an inode with the file you're keeping. - Symlinks. Skip them unconditionally. Following them can create cycles or delete the real target of a link.
- Empty files. Every empty file is trivially equal to every other. Skip files below a minimum size (e.g., 1 byte) by default to avoid spurious matches.
- Files that vanish or become unreadable mid-scan. Catch the
OSError, drop the row, and continue. Don't abort the whole job. - Files modified between hashing and deletion. The re-
statbefore deletion catches mtime or size changes; the byte compare catches content changes that happen to preserve the size. - Permission errors on directories. Log and skip; don't crash.
- Safer alternatives to deletion. Replacing duplicates with hard links (same filesystem only) or moving them to a quarantine directory is often preferable to outright deletion, especially on a first run.
Common mistakes
- Relying on a single hash pass with no byte verification before deletion.
- Using a non-streaming approach that loads whole files into memory.
- Skipping the partial-hash stage and jumping straight to full hashes, which wastes I/O on files that would have been eliminated cheaply.
- Treating hard-linked paths as duplicates and deleting them, which corrupts data without freeing any space.
- Storing all state in process memory, making the job non-resumable and impractical for large trees.