Identify Duplicate Files Across a File System and Analyze System Bottlenecks
System DesignModel answerLast updated
Design an algorithm to find all groups of identical files in a directory tree while handling massive files, edge cases, and analyzing CPU versus disk I/O performance.
Design and implement an efficient program that accepts a root directory path, recursively scans the file system tree beneath it, and groups all regular files that have byte-for-byte identical content.
Core Requirements
- Output each set of identical files as a grouped list of file paths.
- Do not output unique files (files with no duplicates). If no duplicates exist anywhere in the directory tree, the output must be completely empty (no headers, no trailing newlines, no status messages).
- The solution must scale cleanly to millions of files and files that exceed physical RAM capacity.
Key Considerations & Edge Cases
During your explanation, explicitly address:
- Symbolic Links & Hard Links: How should symlinks (and potential directory cycles) and hard links (files sharing the same inode) be handled?
- Special File Types & Permissions: How to handle empty files, unreadable files/directories, and files modified during execution?
- Collision Strategy: Is a cryptographic hash sufficient to determine identity, or is direct comparison required?
- Performance Analysis: Break down which stages are CPU-bound versus I/O-bound, and explain how to design a parallelized pipeline to optimize throughput.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem Overview
Finding duplicate files across a large file system efficiently requires minimizing expensive disk reads and CPU overhead. A naive approach of comparing every file byte-for-byte against every other file leads to an $O(N^2)$ time complexity and massive disk I/O.
To make this optimal and scalable, we apply a multi-stage filtering pipeline that progressively eliminates non-duplicate candidates using cheaper metadata operations before reading raw data.
High-Level Architecture & Algorithm Strategy
We process files through a four-stage pipeline:
[ Directory Walk ] ---> Stage 1: Group by File Size
|
v
Stage 2: Group by Partial Hash (First 4KB)
|
v
Stage 3: Group by Full Cryptographic Hash (SHA-256)
|
v
Stage 4: Byte-by-Byte Verification (Optional / Safety)
Stage 1: File Size Grouping
- Operation: Traverse the directory tree using metadata-only calls (
stat/lstat). - Logic: Collect file sizes into a map:
Map<FileSize, List<FilePath>>. - Optimization: Any size with only one file is immediately discarded. No disk read of file contents occurs.
Stage 2: Partial Hash Grouping
- Operation: For files sharing the same size, read only the first $K$ bytes (e.g., 4 KB).
- Logic: Compute a fast hash (e.g., xxHash or MD5) of the initial block:
Map<(FileSize, PartialHash), List<FilePath>>. - Optimization: Files with different headers are discarded without reading the remainder of the file.
Stage 3: Full Cryptographic Hash Grouping
- Operation: For files sharing size and partial hash, stream the entire file content in fixed-size chunks (e.g., 64 KB) to compute a full cryptographic hash (e.g., SHA-256).
- Logic: Store results in
Map<(FileSize, FullHash), List<FilePath>>.
Stage 4: Byte-by-Byte Verification
- Operation: If absolute mathematical certainty against cryptographic hash collisions is required, perform a chunk-by-chunk binary comparison for remaining candidate groups.
- Logic: Open candidate file pairs in parallel streams and compare matching buffer chunks.
Edge Case Handling
| Scenario | Strategy |
|---|---|
| Symbolic Links | Use lstat instead of stat. Skip symlinks by default to avoid cyclic loops and double-counting target files. If symlinks must be followed, maintain a set of visited canonical paths ((dev_id, inode)). |
| Hard Links | Multiple directory entries can point to the same physical inode ((device, inode)). Track (device_id, inode_id). Decide whether hard links count as duplicates. Standard practice: treat identical physical inodes as the same file and ignore them, or record them explicitly based on product requirements. |
| Zero-Byte Files | Empty files share size 0. Grouping them depends on product requirements. If included, all zero-byte files hash to the same value without requiring disk I/O. |
| Permission Denied / Unreadable Files | Catch I/O exceptions gracefully at the individual file/directory level. Log errors to stderr (or ignore silently) and continue tree traversal without crashing the pipeline. |
| Files Modified Mid-Scan | Re-verify file size/mtime during Stage 3/4. If a file's size changes while reading, discard it from candidate sets. |
Python Implementation
import os
import sys
import hashlib
from collections import defaultdict
PARTIAL_HASH_BYTES = 4096 # 4 KB
CHUNK_SIZE = 65536 # 64 KB
def get_partial_hash(filepath):
"""Hashes only the first PARTIAL_HASH_BYTES of a file."""
hasher = hashlib.md5()
try:
with open(filepath, 'rb') as f:
data = f.read(PARTIAL_HASH_BYTES)
hasher.update(data)
return hasher.hexdigest()
except (PermissionError, OSError):
return None
def get_full_hash(filepath):
"""Hashes the entire file in chunks to bound memory usage."""
hasher = hashlib.sha256()
try:
with open(filepath, 'rb') as f:
while chunk := f.read(CHUNK_SIZE):
hasher.update(chunk)
return hasher.hexdigest()
except (PermissionError, OSError):
return None
def find_duplicate_files(root_dir):
# Stage 1: Group by file size
size_groups = defaultdict(list)
seen_inodes = set()
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
# Use lstat to avoid following symlinks automatically
stat_info = os.lstat(filepath)
# Filter non-regular files (symlinks, sockets, devices)
if not os.path.isfile(filepath) or os.path.islink(filepath):
continue
# Deduplicate physical hard links
inode_key = (stat_info.st_dev, stat_info.st_ino)
if inode_key in seen_inodes:
continue
seen_inodes.add(inode_key)
size_groups[stat_info.st_size].append(filepath)
except (PermissionError, OSError):
continue
# Keep sizes with >1 candidate
candidate_size_groups = [paths for size, paths in size_groups.items() if len(paths) > 1]
# Stage 2: Group by Partial Hash
partial_hash_groups = defaultdict(list)
for paths in candidate_size_groups:
for path in paths:
p_hash = get_partial_hash(path)
if p_hash:
# Group key combines file size and partial hash
size = os.path.getsize(path)
partial_hash_groups[(size, p_hash)].append(path)
candidate_partial_groups = [paths for paths in partial_hash_groups.values() if len(paths) > 1]
# Stage 3: Group by Full Hash
full_hash_groups = defaultdict(list)
for paths in candidate_partial_groups:
for path in paths:
f_hash = get_full_hash(path)
if f_hash:
full_hash_groups[f_hash].append(path)
# Filter final duplicates
duplicates = [paths for paths in full_hash_groups.values() if len(paths) > 1]
return duplicates
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
root_directory = sys.argv[1]
duplicate_sets = find_duplicate_files(root_directory)
for group in duplicate_sets:
print(" ".join(group))
Complexity & System Bottleneck Analysis
Complexity Analysis
- Time Complexity:
- Best Case (No duplicate sizes): $O(N)$ directory metadata queries (
stat), where $N$ is total files. 0 bytes of content read. - Worst Case (All files identical): $O(N \cdot M)$ where $M$ is average file size in bytes.
- Best Case (No duplicate sizes): $O(N)$ directory metadata queries (
- Space Complexity: $O(N)$ memory to store file paths and metadata keys in hash maps. File content memory remains $O(1)$ due to chunked streaming.
Bottleneck Breakdown: CPU vs. Disk I/O
+------------------------+-------------------+--------------------+
| Stage | Bottleneck | System Constraint |
+------------------------+-------------------+--------------------+
| 1. Directory Traversal | I/O-bound | Metadata Seek/Ops |
| 2. Partial Hashing | Disk Random I/O | IOPS (Seek Time) |
| 3. Full Hashing | CPU or Sequent.IO | Bus/Drive Read MB/s|
| 4. Direct Comparison | Disk Sequential | Read Throughput |
+------------------------+-------------------+--------------------+
- Stage 1 (Traversal): Entirely I/O-bound due to filesystem metadata lookups (
readdir/stat). On HDDs, this causes severe head-seeking overhead. - Stage 2 (Partial Read): Disk Latency / IOPS-bound. Reading small 4 KB blocks scattered randomly across different disk locations relies heavily on IOPS (Input/Output Operations Per Second).
- Stage 3 (Full Read & Hash):
- On fast NVMe SSDs (3–7 GB/sec read speeds), computing SHA-256 hashes on a single core at ~500 MB/sec makes the job CPU-bound.
- On spinning HDDs (~150 MB/sec sequential speed), the job is I/O-bound.
Concurrent Architecture Optimization
To optimize throughput on modern hardware:
- Use a Producer-Consumer Thread Pool architecture.
- Worker pool isolation: Use separate worker queues for metadata scanning, disk reading, and CPU hash calculations.
- Storage-aware concurrency: For HDDs, limit concurrent reader threads to 1–2 to prevent disk head trashing. For NVMe SSDs, use $N$ worker threads matching available CPU cores to saturate bus bandwidth and maximize hash throughput.