Content-Based Duplicate File Detector
Trees & GraphsModel answerLast updated
Recursively scan a directory tree, group files by size then content hash, and return every set of two or more paths that hold identical bytes.
Content-Based Duplicate File Detector
You are building a storage-cleanup utility. Given a path to a root directory, write a function that finds every group of files whose contents are byte-for-byte identical and returns those groups.
Function signature
def find_duplicates(root: str) -> list[list[str]]:
...
What to return
A list of groups. Each group is a sorted list of absolute (or root-relative) paths. Only groups with at least two members should appear. The outer list should also be sorted. Return an empty list when no duplicates exist.
Requirements
- Traverse the directory tree recursively, including all subdirectories.
- Use file size as a first filter — files with different sizes cannot be identical.
- For files that share a size, use a content hash to identify matches.
- Never load an entire file into memory at once; use fixed-size read buffers so the solution works on arbitrarily large files.
- If a file cannot be read (permission denied, deleted mid-scan, etc.) skip it and continue — do not crash.
- If a file changes while it is being hashed, discard it from results rather than reporting a potentially inconsistent hash.
Example
root/
a.txt ("hello")
b.txt ("hello")
sub/
c.txt ("hello")
d.txt ("world")
find_duplicates("root")
# → [["root/a.txt", "root/b.txt", "root/sub/c.txt"]]
d.txt has no duplicate, so it does not appear.
Constraints
- The tree can be arbitrarily deep.
- Files can range from 0 bytes to many gigabytes.
- The directory may contain symlinks, hard links, FIFOs, and other non-regular entries.
- Assume a single machine for the base solution; scaling questions are discussed as follow-ups.
Follow-up discussion (no code needed, talk through the ideas)
- Is this workload I/O-bound or CPU-bound, and how would you find out?
- How would you handle files that are hundreds of gigabytes?
- How would you scale to a filesystem with billions of files?
- Where would you introduce parallelism, and what are the risks?
- How would you support near-real-time detection as files arrive or change?
Hints
Hint 1
Before reading any bytes, group files by the size reported in their metadata. A stat call costs almost nothing and immediately eliminates files that cannot possibly match anything.
Hint 2
Reading the entire content of every same-size file is wasteful. Hash only the first 64 KB first — files that differ early are eliminated after a tiny read, and only survivors go on to a full hash.
Hint 3
When you open a file for hashing, check its size and modification time before and after reading. If either changed, the hash describes a moving target and should be thrown away, not returned as a result.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Comparing every pair of files byte by byte is O(n²) in reads and completely impractical. The better strategy is a narrowing funnel: each stage does a little cheap work that eliminates files that cannot have a duplicate, so the expensive full-content hash runs on as few files as possible.
Stage 1 — group by size. os.stat (or os.scandir, which piggybacks on the directory entry) gives the file size without opening the file. Files with different sizes cannot be identical. In a typical filesystem the vast majority of files have a unique size, so this single filter eliminates most of the work before any I/O happens on file contents.
Stage 2 — group by prefix hash. For each same-size bucket with two or more members, hash only the first 64 KB of each file using BLAKE2b. Files that differ somewhere in their opening bytes are cheap to eliminate; only groups that match on the prefix survive.
Stage 3 — group by full hash. Survivors are hashed completely, reading in 1 MiB chunks so memory usage stays constant regardless of file size.
Emit results. Any group still containing two or more paths after the full hash is a duplicate set.
Correctness
- No false negatives: identical files always agree on size, prefix hash, and full hash, so no true duplicate is ever separated.
- False positives require a BLAKE2b-256 collision, which is negligible in practice. If the application demands absolute certainty, a final byte-by-byte comparison within each full-hash bucket is cheap because it only touches near-certain matches.
- Stability: after hashing, compare the file's size and mtime via
fstaton the still-open handle. A mismatch means the file changed during the read; drop it and log the path.
Complexity
Let N = number of files, B = total bytes belonging to files that share a size with at least one other file.
- Time: O(N) for the walk and stat calls, plus O(B) bytes hashed in the worst case. The prefix stage typically makes B much smaller than total filesystem bytes.
- Space: O(N) for the in-memory maps, plus O(chunk) for read buffers. File contents are never accumulated in memory.
Edge Cases
- Zero-byte files. All of them are identical. No hashing is needed; they fall into a single size-zero bucket automatically.
- Files smaller than the prefix size. The prefix hash and full hash would read the same bytes. Skip straight to the full hash.
- Symlinks. Do not follow them (
follow_symlinks=False). Following symlinks risks cycles and double-reporting one physical file under two names. - Hard links. Two paths sharing an inode are content-identical and will be reported. If the goal is to free disk space, deduplicate by
(st_dev, st_ino)first, because removing a hard link does not free the underlying blocks until the last link is gone. - Non-regular files. Skip FIFOs, sockets, and block devices. Reading a FIFO blocks indefinitely.
- Errors mid-scan. Unreadable directories and permission-denied files are collected in an errors list and skipped; the scan never aborts.
Python Solution
import hashlib
import os
from collections import defaultdict
CHUNK = 1 << 20 # 1 MiB read buffer
PREFIX = 64 * 1024 # bytes read for the cheap first-pass hash
def _walk(root, errors):
"""Iterative directory walk; yields (path, stat_result) for regular files."""
stack = [root]
while stack:
current = stack.pop()
try:
with os.scandir(current) as it:
for entry in it:
try:
if entry.is_dir(follow_symlinks=False):
stack.append(entry.path)
elif entry.is_file(follow_symlinks=False):
yield entry.path, entry.stat(follow_symlinks=False)
except OSError as exc:
errors.append((entry.path, str(exc)))
except OSError as exc:
errors.append((current, str(exc)))
def _hash(path, st, limit=None):
"""
Hash up to `limit` bytes of path (entire file if limit is None).
Raises OSError if the file cannot be read.
Raises ValueError if the file changed during the read.
"""
h = hashlib.blake2b(digest_size=32)
remaining = st.st_size if limit is None else min(limit, st.st_size)
with open(path, "rb") as fh:
while remaining > 0:
chunk = fh.read(min(CHUNK, remaining))
if not chunk:
break # file was truncated; fstat check below will catch it
h.update(chunk)
remaining -= len(chunk)
after = os.fstat(fh.fileno())
if (after.st_size, after.st_mtime_ns) != (st.st_size, st.st_mtime_ns):
raise ValueError(f"file changed during hashing: {path}")
return h.digest()
def _split_by_hash(files, limit, errors):
"""Hash each file up to `limit` bytes; return buckets with >= 2 members."""
buckets = defaultdict(list)
for path, st in files:
try:
key = _hash(path, st, limit)
buckets[key].append((path, st))
except (OSError, ValueError) as exc:
errors.append((path, str(exc)))
return [g for g in buckets.values() if len(g) > 1]
def find_duplicates(root: str) -> list[list[str]]:
errors: list[tuple[str, str]] = []
# Stage 1: group by file size (pure metadata, no content reads)
by_size: dict[int, list] = defaultdict(list)
for path, st in _walk(root, errors):
by_size[st.st_size].append((path, st))
result = []
for size, files in by_size.items():
if len(files) < 2:
continue
# Stage 2: skip prefix pass when files are tiny
if size <= PREFIX:
candidates = [files]
else:
candidates = _split_by_hash(files, PREFIX, errors)
# Stage 3: full-content hash on survivors
for group in candidates:
for dup_group in _split_by_hash(group, None, errors):
result.append(sorted(p for p, _ in dup_group))
return sorted(result)
The walk is iterative, so deep trees do not overflow Python's recursion limit.
Follow-up Discussion
I/O-bound or CPU-bound? The scan is almost always I/O-bound: metadata calls and sequential reads dominate, especially on spinning disks or network storage. Hashing can become CPU-bound on NVMe drives (3+ GB/s reads, ~0.5 GB/s per core for SHA-256). To find out: compare wall time to CPU time — a large gap means I/O is the bottleneck. Watch iostat for device saturation. Profile with py-spy. If CPU-bound, switch to a faster hash like BLAKE3 or xxHash128 and add worker threads.
Very large files. Chunked streaming already keeps memory constant. Add intermediate sample hashes at the midpoint and tail to catch late-diverging files before the full pass. Use posix_fadvise(SEQUENTIAL) for better prefetch behavior. BLAKE3's tree structure allows parallel hashing of a single file across cores.
Billions of files. The in-memory size map becomes the limiting factor. Stream (size, path) records to disk and sort-merge externally rather than holding everything in RAM. Distribute the scan across machines by subtree, aggregate hash buckets centrally, and store results in a database.
Parallelism. The walk is single-threaded by design (directory entry ordering matters less than avoiding races). Hashing is embarrassingly parallel: dispatch each file to a ThreadPoolExecutor (I/O-bound) or ProcessPoolExecutor (CPU-bound on NVMe). Be careful about too many concurrent opens on HDDs — sequential access on one spindle is faster than random seeks from many threads.
Near-real-time detection. Use filesystem event APIs (inotify on Linux, FSEvents on macOS, ReadDirectoryChangesW on Windows) to receive CREATE and MODIFY events. On each event, run the same size-then-hash funnel for the affected file against an index of already-known hashes. Keep the index in a fast key-value store (e.g., SQLite or Redis) rather than rebuilding from scratch.