Detect Duplicate Files Safely and Efficiently
Data Structure DesignModel answerLast updated
Design a filesystem duplicate finder that guards against infinite loops, avoids loading whole files into memory, and applies multi-stage filtering to minimize disk reads.
Create a duplicate file analyzer that explores a specified root directory and groups together files containing identical byte sequences.
Your implementation must be resilient against filesystem anomalies (such as directory symlink loops), preserve memory limits when inspecting large files, and minimize redundant disk input/output (I/O).
Requirements
- Safety Against Cycles and Hard Links:
- Safely navigate symbolic links without getting trapped in infinite recursion.
- Distinct file paths pointing to the exact same physical inode (
(st_dev, st_ino)) represent hard links to a single underlying file. Choose one representative path per physical file rather than classifying hard links as duplicate copies of one another.
- Layered Content Inspection:
- Stage 1 (File Size): Group candidate files by size using filesystem metadata. Singletons are discarded immediately.
- Stage 2 (Prefix Hash): For remaining files, compute a hash of the initial prefix (e.g., the first 4 KB).
- Stage 3 (Full Content Hash): For candidates with identical prefix hashes, read the full content using streaming chunks to compute an overall hash (e.g., SHA-256). Skip this step if the total file size is less than or equal to the prefix size.
- Stage 4 (Optional Exact Byte Comparison): Support a strict byte-by-byte check option to eliminate any possibility of hash collisions.
- Memory Bounding:
- Stream content using a configurable buffer size (
chunk_size) to handle multi-gigabyte files safely without consuming excessive RAM.
- Stream content using a configurable buffer size (
Interface
from typing import List
class ScalableDuplicateFinder:
def __init__(
self,
chunk_size: int = 64 * 1024,
prefix_size: int = 4096,
include_empty: bool = False,
follow_symlinks: bool = False,
verify_bytes: bool = False,
):
"""
chunk_size: Bytes to read per buffer streaming iteration.
prefix_size: Bytes to inspect for the initial partial hash.
include_empty: Whether to group 0-byte files as duplicates.
follow_symlinks: Whether to traverse directory symlinks safely.
verify_bytes: Perform exact byte-by-byte comparison to confirm hash matches.
"""
pass
def find_duplicates(self, root_dir: str) -> List[List[str]]:
"""
Recursively scans root_dir and returns groups of duplicate file paths.
Each inner list contains two or more paths representing identical content.
"""
pass
Example
Given the directory structure:
/data/
├── doc_a.txt (10 bytes, content: "helloworld")
├── doc_b.txt (10 bytes, content: "helloworld")
├── doc_c.txt (10 bytes, content: "foobar1234")
└── subfolder/
├── doc_d.txt (10 bytes, content: "helloworld")
└── link_to_root -> /data
Output:
[
["/data/doc_a.txt", "/data/doc_b.txt", "/data/subfolder/doc_d.txt"]
]
Constraints & Edge Cases
- 0-Byte Files: Controlled by
include_empty. IfFalse, 0-byte files are ignored. - Inaccessible Files: Permission errors, missing entries, or unreadable blocks must be skipped without stopping traversal.
- Cycle Safety: Symlink loops must not crash or hang the traversal.
- Special Objects: Non-regular files (pipes, sockets, device nodes) must be skipped.
Hints
Hint 1
How can you track visited directories across symlinks to prevent infinite recursive loops?
Hint 2
Why is filtering by file size first much more efficient than hashing files immediately?
Hint 3
What is the difference between physical duplicates and multiple hard links sharing the same (device, inode) pair?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The solution uses a funnel approach, where cheap operations eliminate the vast majority of non-duplicate candidates before executing expensive disk reads:
-
Iterative Traversal with Inode Tracking:
- Walk the directory structure using an explicit stack to avoid recursion depth limits.
- Track visited directories by their
(device, inode)tuple. This guarantees that symlink cycles are detected and bypassed even whenfollow_symlinks=True. - Track seen regular file inodes. If multiple path references hit the same
(device, inode), keep only the first path to ignore duplicate hard-link references.
-
Stage 1: Size Categorization:
- Fetch metadata via
stat(). Group candidate paths by file size. - File size buckets containing fewer than 2 files are discarded immediately without touching file contents.
- Fetch metadata via
-
Stage 2: Prefix Hash (Partial I/O):
- For size buckets with multiple files, read up to
prefix_size(e.g., 4 KB) and compute a hash (e.g., SHA-256). - Group files by prefix hash.
- For size buckets with multiple files, read up to
-
Stage 3: Full Hash (Streaming I/O):
- If a file's size is $\le$
prefix_size, the prefix hash was already a full content hash. - For larger files in buckets with matching prefixes, stream the remainder of the file in
chunk_sizeblocks (e.g., 64 KB) to construct a full content hash.
- If a file's size is $\le$
-
Stage 4: Optional Byte-by-Byte Verification:
- To eliminate cryptographic hash collision risks, partition full-hash candidate buckets into exact byte-equivalence classes by comparing buffers sequentially.
Python Source Code
import hashlib
import os
from collections import defaultdict
from typing import Callable, Dict, List, Optional, Set, Tuple
class ScalableDuplicateFinder:
def __init__(
self,
chunk_size: int = 64 * 1024,
prefix_size: int = 4096,
include_empty: bool = False,
follow_symlinks: bool = False,
verify_bytes: bool = False,
):
if chunk_size <= 0 or prefix_size <= 0:
raise ValueError("chunk_size and prefix_size must be positive integers.")
self.chunk_size = chunk_size
self.prefix_size = prefix_size
self.include_empty = include_empty
self.follow_symlinks = follow_symlinks
self.verify_bytes = verify_bytes
def find_duplicates(self, root_dir: str) -> List[List[str]]:
results: List[List[str]] = []
size_groups = self._collect_files_by_size(root_dir)
for size, paths in size_groups.items():
if len(paths) < 2:
continue
if size == 0:
if self.include_empty:
results.append(sorted(paths))
continue
# Stage 2: Prefix Hashing
prefix_buckets = self._partition(
paths, lambda p: self._hash_file(p, max_bytes=self.prefix_size)
)
for prefix_group in prefix_buckets:
if len(prefix_group) < 2:
continue
# Stage 3: Full Hashing (skip if prefix already covered whole file)
if size <= self.prefix_size:
full_groups = [prefix_group]
else:
full_groups = self._partition(
prefix_group, lambda p: self._hash_file(p, max_bytes=None)
)
for candidate_group in full_groups:
if len(candidate_group) < 2:
continue
# Stage 4: Byte Verification (optional)
if self.verify_bytes:
results.extend(self._verify_exact_bytes(candidate_group))
else:
results.append(sorted(candidate_group))
results.sort()
return results
def _collect_files_by_size(self, root_dir: str) -> Dict[int, List[str]]:
by_size: Dict[int, List[str]] = defaultdict(list)
visited_dirs: Set[Tuple[int, int]] = set()
seen_files: Set[Tuple[int, int]] = set()
try:
root_stat = os.stat(root_dir)
visited_dirs.add((root_stat.st_dev, root_stat.st_ino))
except OSError:
return by_size
stack = [root_dir]
follow = self.follow_symlinks
while stack:
current_dir = stack.pop()
try:
with os.scandir(current_dir) as iterator:
entries = sorted(iterator, key=lambda e: e.name)
except OSError:
continue
for entry in entries:
try:
is_dir = entry.is_dir(follow_symlinks=follow)
is_file = entry.is_file(follow_symlinks=follow)
if is_dir:
st = entry.stat(follow_symlinks=follow)
dir_key = (st.st_dev, st.st_ino)
if dir_key not in visited_dirs:
visited_dirs.add(dir_key)
stack.append(entry.path)
elif is_file:
st = entry.stat(follow_symlinks=follow)
file_key = (st.st_dev, st.st_ino)
if file_key not in seen_files:
seen_files.add(file_key)
by_size[st.st_size].append(entry.path)
except OSError:
continue
return by_size
def _partition(
self, paths: List[str], key_fn: Callable[[str], Optional[str]]
) -> List[List[str]]:
groups: Dict[str, List[str]] = defaultdict(list)
for path in paths:
k = key_fn(path)
if k is not None:
groups[k].append(path)
return [g for g in groups.values() if len(g) >= 2]
def _hash_file(self, path: str, max_bytes: Optional[int]) -> Optional[str]:
hasher = hashlib.sha256()
bytes_read = 0
try:
with open(path, "rb") as f:
while True:
if max_bytes is not None:
to_read = min(self.chunk_size, max_bytes - bytes_read)
if to_read <= 0:
break
else:
to_read = self.chunk_size
chunk = f.read(to_read)
if not chunk:
break
hasher.update(chunk)
bytes_read += len(chunk)
except OSError:
return None
return hasher.hexdigest()
def _verify_exact_bytes(self, paths: List[str]) -> List[List[str]]:
classes: List[List[str]] = []
for path in paths:
matched = False
for cls in classes:
if self._are_files_equal(path, cls[0]):
cls.append(path)
matched = True
break
if not matched:
classes.append([path])
return [sorted(cls) for cls in classes if len(cls) >= 2]
def _are_files_equal(self, path1: str, path2: str) -> bool:
try:
with open(path1, "rb") as f1, open(path2, "rb") as f2:
while True:
b1 = f1.read(self.chunk_size)
b2 = f2.read(self.chunk_size)
if b1 != b2:
return False
if not b1:
return True
except OSError:
return False
Complexity Analysis
- Time Complexity:
- Directory Traversal: $\mathcal{O}(N)$ file system metadata accesses, where $N$ is the number of files and directories.
- Hashing Phase: $\mathcal{O}(M \cdot K)$, where $M$ is the number of files surviving size filtering and $K$ is the bytes read (ranging from $4\text{ KB}$ for prefix hashing up to the total file size for full content hashing).
- Byte Verification Phase: $\mathcal{O}(C \cdot S)$ worst-case per group, where $C$ is candidate paths in a bucket of size $S$.
- Space Complexity:
- $\mathcal{O}(N)$ memory to hold track of directory keys
(st_dev, st_ino)and unique file paths. - $\mathcal{O}(\text{chunk_size})$ heap memory during active file I/O operations.
- $\mathcal{O}(N)$ memory to hold track of directory keys