KatInterview

Detect Duplicate Files Safely and Efficiently

Data Structure DesignModel answer
MediumModel answerData Structure Designfilesystemhashingio-optimization

Last 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

  1. 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.
  2. 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.
  3. Memory Bounding:
    • Stream content using a configurable buffer size (chunk_size) to handle multi-gigabyte files safely without consuming excessive RAM.

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. If False, 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?