Finding Identical Files in a Huge Directory Tree
System DesignModel answerLast 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 ofbytespieces for that file. Chunk sizes may be irregular.
Requirements
- 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.
- Be safe against hash collisions. The output must never contain two files that differ.
- Support datasets whose metadata and contents do not fit in memory.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea: a funnel of increasingly costly filters
Two files can only be identical if they agree on every cheaper property first. Each stage splits the candidates into smaller groups, and any group with a single member is discarded. Expensive reads are therefore spent only on files that are still plausible duplicates.
- Group by size (metadata only). A file with a unique size has no duplicate. In real trees this eliminates most files without opening them.
- Hash a prefix. Within each size group, hash the first block (for example 64 KB). Files with different headers separate cheaply. If the file is no larger than one block, this hash covers the whole file.
- Hash the full content. Within each prefix group, stream the whole file through SHA-256. The 32-byte digest is a compact fingerprint that is easy to ship between machines.
- Verify byte for byte. Within each full-hash group, read all files in lockstep, block by block, and split the group whenever blocks differ. Only files that reach end-of-file together are reported.
Rolling hashes (Rabin-Karp, Buzhash) matter for content-defined chunking, where shifted content must still match. For whole-file equality, a fixed-offset cryptographic hash is simpler and stronger. Name the distinction, then pick the right tool.
Why it is correct
- No missed duplicates. Identical files share size, prefix and digest, so stages 1 to 3 never separate them. Stage 4 separates files only when some byte differs at the same offset.
- No false groups. The final decision comes from direct byte comparison, not from hashes. A collision, accidental or adversarial, costs at most extra work and can never yield a wrong answer.
- All files in a group have equal size, so their streams hit EOF at the same block. Reaching EOF together means every byte matched.
Handling data larger than memory
The only structure that can grow without bound is the size-to-paths index. Use an external hash partition:
- Stream
(path, size)once, appending each record to one ofPspill files chosen byhash(size) % P. - All files with the same size land in the same partition, so each partition can be loaded and processed alone. Memory is bounded by about
N / Precords. - Yield result groups as they are produced rather than accumulating them.
- Hashing and comparison use fixed-size blocks, so per-file memory is O(BLOCK).
For a very large group, opening every file at once may exceed the file-descriptor limit. In that case verify in batches, comparing each batch against a representative file, or lean on the full digests to split the group first.
Complexity and trade-offs
Let N be the number of files, S the total bytes, and S_c the bytes in files that survive the size and prefix filters.
- Time: O(N) to partition and group. Hashing costs O(N_c * BLOCK + S_c), and verification O(S_c). In practice disk I/O dominates.
- I/O: files with a unique size are never read. True duplicates are read twice, once to hash and once to verify.
- Space: O(N / P) records per partition, plus O(BLOCK * group size) while verifying.
Options worth discussing:
- Skip the full hash. After the prefix filter, lockstep comparison alone reads each candidate once, which is I/O optimal. The full hash is still valuable when groups are too large to open together, or when work is distributed and you want to compare digests instead of moving bytes.
- Skip verification. If the policy accepts SHA-256 (collision probability around 2^-128), you halve I/O on duplicates. Present this as an explicit risk decision, not as a correctness argument.
- Prefix size. A bigger prefix filters better but costs more per candidate. 4 to 64 KB is typical. Hashing the last block as well helps for formats with shared headers, such as media containers.
Parallelization
- Hashing is I/O-bound, so a thread pool or async I/O works well. Python's
hashlibreleases the GIL on large buffers. - Size partitions, and later hash groups, share no state, so they can be sent to separate processes or machines. This maps cleanly to MapReduce: key by size, then by
(size, prefix hash), then by(size, full hash), and finally verify on a node near the data. - On spinning disks, avoid seek thrash by ordering reads by directory or physical location and capping concurrent readers per device.
Edge cases
- Empty files: all zero-byte files are identical, so group them without reading.
- Hard links: the same
(device, inode)is trivially the same content. Optionally collapse these before reading. - Symlinks: choose a policy, usually do not follow, to avoid double counting and loops.
- Files changing mid-scan: recheck size or mtime at read time and drop or flag files that changed.
- Unreadable files: catch the error, skip the file, report it, and continue.
- Irregular chunk sizes: re-block each stream into fixed-size blocks so lockstep comparison lines up.
Reference code
import hashlib
from collections import defaultdict
from typing import Callable, Iterable, Iterator, List
BLOCK = 64 * 1024
def blocks(chunks: Iterable[bytes], size: int = BLOCK) -> Iterator[bytes]:
"""Re-chunk an arbitrary byte stream into fixed-size blocks."""
buf = bytearray()
for c in chunks:
buf += c
while len(buf) >= size:
yield bytes(buf[:size])
del buf[:size]
if buf:
yield bytes(buf)
def refine(groups, key_fn):
"""Split each group by key_fn and drop singletons."""
for group in groups:
buckets = defaultdict(list)
for p in group:
try:
buckets[key_fn(p)].append(p)
except OSError:
continue # unreadable file: skip
for g in buckets.values():
if len(g) > 1:
yield g
def verify(paths: List[str], read_chunks) -> List[List[str]]:
"""Lockstep comparison; split on the first differing block."""
streams = {p: blocks(read_chunks(p)) for p in paths}
pending, result = [list(paths)], []
while pending:
group = pending.pop()
buckets = defaultdict(list)
for p in group:
buckets[next(streams[p], None)].append(p)
for blk, ps in buckets.items():
if len(ps) < 2:
continue
if blk is None: # all hit EOF together
result.append(ps)
else:
pending.append(ps)
return result
def find_duplicates(files: Iterable[tuple], read_chunks: Callable) -> Iterator[List[str]]:
by_size = defaultdict(list) # replace with spill partitions at scale
for path, size in files:
by_size[size].append(path)
for size, paths in by_size.items():
if len(paths) < 2:
continue
if size == 0:
yield paths
continue
def prefix_hash(p):
first = next(blocks(read_chunks(p)), b"")
return hashlib.sha256(first).digest()
def full_hash(p):
h = hashlib.sha256()
for b in blocks(read_chunks(p)):
h.update(b)
return h.digest()
for g in refine(refine([paths], prefix_hash), full_hash):
yield from verify(g, read_chunks)
Common mistakes
- Trusting a hash match as proof of equality.
- Hashing every file in full before checking sizes.
- Reading whole files into memory instead of streaming.
- Assuming
read_chunksyields equal-sized pieces, which breaks lockstep comparison. - Ignoring hard links, symlinks and unreadable files.