Detecting Deletable Byte-Identical Files

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A local storage volume holds up to millions of user files of arbitrary sizes. Two files count as duplicates if and only if their raw byte sequences match from start to finish—perceptual similarity, filenames, directory locations, permission bits, and modification timestamps never determine equality.

Implement find_deletable_duplicates(paths: List[str]) -> Set[str], which inspects a list of candidate path strings on a single machine and returns the set of paths that can be safely removed without losing any unique file content. The function is strictly read-only: it must never delete, rename, or alter anything on disk.

Follow these exact rules:

  1. Eligible files: Inspect each entry with os.lstat (do not follow symbolic links). Keep only readable, regular files (stat.S_ISREG) whose byte length is strictly positive (st_size > 0). Silently skip missing or unreadable paths, directories, symbolic links, device/socket files, and 0-byte files.
  2. Physical inode identity: Multiple input strings pointing to the same physical disk object (st_dev, st_ino)—such as repeated entries, equivalent relative paths like "a/./b" and "a/b", or POSIX hard links—refer to a single stored file rather than duplicates. Represent each (st_dev, st_ino) inode by its lexicographically smallest path string so results never depend on the order of paths.
  3. Canonical survivor selection: Within every group of two or more byte-identical physical files, retain one canonical survivor and mark every other file in that group as deletable:
    • Keep the copy with the earliest modification timestamp (smallest st_mtime_ns).
    • Break timestamp ties by keeping the lexicographically smallest path string (path_a < path_b).
  4. I/O efficiency and collision safety: Avoid reading uniquely sized files from disk, stream file reads in bounded chunks rather than loading entire files into RAM, and verify candidate duplicates byte for byte against their chosen canonical survivor so hash collisions or mid-scan edits cannot cause false deletions. If any OSError occurs while reading a file, skip it safely rather than marking it for deletion.

Examples

Example 1

Suppose /archive contains four regular 1,200-byte files:

  • "/archive/2021/report.pdf" — bytes b"Q1-summary" * 120, mtime = 100s
  • "/archive/downloads/report_copy.pdf" — bytes b"Q1-summary" * 120, mtime = 250s
  • "/archive/export/doc_01.pdf" — bytes b"Q1-summary" * 120, mtime = 100s
  • "/archive/2022/report.pdf" — bytes b"Q2-summary" * 120, mtime = 90s
paths = [
    "/archive/downloads/report_copy.pdf",
    "/archive/2022/report.pdf",
    "/archive/export/doc_01.pdf",
    "/archive/2021/report.pdf",
]
find_deletable_duplicates(paths)
# -> {"/archive/export/doc_01.pdf", "/archive/downloads/report_copy.pdf"}

Walk-through: Even though "/archive/2022/report.pdf" shares the 1,200-byte size and report.pdf basename, its contents differ so it is left alone. The other three files hold identical bytes. Two of them tie at the earliest modification time (100s), and "/archive/2021/report.pdf" comes before "/archive/export/doc_01.pdf" lexicographically, so "/archive/2021/report.pdf" survives while the remaining two copies are returned.

Example 2

Suppose /vault contains:

  • "/vault/master.bin" — 64 bytes (b"payload-v1" + b"\x00" * 54), mtime = 500s
  • "/vault/hardlink_master.bin" — POSIX hard link (os.link) to "/vault/master.bin"
  • "/vault/aaa_shortcut.bin" — symbolic link (os.symlink) pointing to "/vault/master.bin"
  • "/vault/clone.bin" — separate regular file with the same 64 bytes, mtime = 800s
  • "/vault/empty_a.lock" and "/vault/empty_b.lock" — two 0-byte regular files
  • "/vault/missing.bin" — path does not exist
paths = [
    "/vault/aaa_shortcut.bin",
    "/vault/master.bin",
    "/vault/hardlink_master.bin",
    "/vault/clone.bin",
    "/vault/empty_a.lock",
    "/vault/empty_b.lock",
    "/vault/missing.bin",
]
find_deletable_duplicates(paths)
# -> {"/vault/clone.bin"}

Walk-through: The missing path, the symbolic link, and both 0-byte .lock files are ignored. "/vault/master.bin" and "/vault/hardlink_master.bin" share one (st_dev, st_ino) inode and collapse into a single physical file (mtime = 500s). Between that physical file and "/vault/clone.bin" (mtime = 800s), the older file is kept and only "/vault/clone.bin" is marked deletable.

Constraints

  • 0 <= len(paths) <= 10^6 in typical single-host workloads; individual files may be tens of gigabytes, so per-file content buffers must use O(1) memory via chunked streaming.
  • Inode identity must pair both device and inode number (st_dev, st_ino).
  • find_deletable_duplicates must not mutate the filesystem.

Step-by-step walkthrough

  1. Clarify the contract and edge-case rules

    Before writing any code, separate deciding what is safe to delete from performing deletions on disk. Our function inspects a list of candidate paths and returns a set of paths that are safe to remove:

    def find_deletable_duplicates(paths: List[str]) -> Set[str]:
        ...
    

    State every rule explicitly up front:

    • Bytes alone define duplicates. Two files are duplicates if and only if their byte sequences are identical from start to finish. Filenames, folders, permissions, and timestamps never make two different files equal and never prevent two byte-identical files from matching.
    • Exactly one copy survives per duplicate group. If three files hold the exact same bytes, we keep one canonical (chosen master) path and mark the other two as deletable.
    • Deterministic tie-breaking. Keep the copy with the oldest modification time (smallest mtime_ns), breaking ties by the lexicographically smallest path string. Re-running the scan on the same disk must always choose the exact same survivor.
    • Ignore non-regular and empty paths. Skip missing or unreadable paths, directories, special device files, symbolic links (pointer files that name another path — keeping a symlink while deleting its target leaves a broken link and loses the underlying data!), and 0-byte files (usually intentional marker files like .gitkeep or .lock).
    • One inode equals one physical file. On Unix/POSIX filesystems, an inode (st_dev, st_ino) identifies the actual data blocks on disk. Passing the same path twice, "2021/./report.pdf" alongside "2021/report.pdf", or two hard links (two directory entries pointing to one inode) reaches a single stored file, not two copies.
  2. Why naive approaches waste disk I/O

    Suppose a machine holds N = 2,000,000 archived files averaging 4 MB each (8 TB total) on a hard drive capable of 200 MB/s sequential reads:

    1. Pairwise byte comparison (O(N^2) pairs): Comparing every pair checks roughly 2 * 10^12 pairs — completely infeasible.
    2. Full-file hashing up front (O(N) files, 100% disk read): Computing SHA-256 over every file reads all 8 TB from disk:
    Total bytes:  2,000,000 files * 4 MB  =  8,000,000 MB  (8 TB)
    Read time:    8,000,000 MB / 200 MB/s =  40,000 s      (~11.1 hours)
    

    Most of those 11 hours are wasted! If only one file on the entire disk is 3,841,209 bytes long, it cannot possibly match any other file — we never needed to open it at all.

  3. Core idea: a multi-stage filtering funnel

    Instead of paying for expensive full-file reads immediately, pass files through a funnel of progressively more expensive checks. A group only advances to the next stage when at least two files still share the exact same signature:

    2,000,000 paths
       |
       |  Stage 0: lstat + skip non-regular/empty/same-inode
       v
    Stage 1: Group by exact byte size (metadata only, 0 content bytes read)
       |  Keep buckets of 2+  (e.g., 300,000 candidates remain)
       v
    Stage 2: Hash first 4 KiB (SHA-256 of bytes 0..4095)
       |  Keep buckets of 2+  (e.g., 100,000 candidates remain)
       v
    Stage 3: Hash full file streamed in 1 MiB chunks (skip if size <= 4 KiB!)
       |  Keep buckets of 2+  (only candidate duplicate groups remain)
       v
    Stage 4: Sort by (mtime_ns, path), pick keeper, verify byte-by-byte
    

    With those illustrative numbers (15% sharing a size, 5% surviving the 4 KiB prefix hash as 50,000 duplicate pairs):

    Stage 2: 300,000 * 4 KiB         ~= 1.2 GB   (~50 min on 100-seek/s HDD; seconds on SSD)
    Stage 3: 100,000 * 4 MB          =  400 GB   (~33 min at 200 MB/s)
    Stage 4: 50,000 pairs * 2 * 4 MB =  400 GB   (~33 min, less when keepers stay cached in RAM)
    

    Total runtime drops from ~11 hours to ~2 hours on a spinning disk (and just minutes on an NVMe SSD). Notice one neat optimization in Stage 3: if a group's file size is <= 4,096 bytes, Stage 2 already hashed the entire file, so Stage 3 skips re-reading it.

  4. Collect usable files and deduplicate inodes

    First, scan paths once using os.lstat (never os.stat, which follows symlinks to their targets). We identify each physical file on disk by (info.st_dev, info.st_ino) because inode numbers are only unique within one mounted device (st_dev).

    If two paths in paths refer to the same inode (such as two hard links), we keep the lexicographically smallest path so our tie-breaking never depends on the order of the input list:

    from typing import Dict, List, Set, Tuple
    import os
    import stat
    
    
    def collect_files(paths: List[str]) -> Dict[str, Tuple[int, int]]:
        # best_by_inode: {(st_dev, st_ino): (smallest_path, size_bytes, mtime_ns)}
        best_by_inode: Dict[Tuple[int, int], Tuple[str, int, int]] = {}
    
        for path in paths:
            try:
                # Use lstat so symlinks are inspected as links rather than followed.
                info = os.lstat(path)
            except OSError:
                continue
    
            # Ignore directories, sockets, devices, symlinks, and 0-byte marker files.
            if not stat.S_ISREG(info.st_mode) or info.st_size == 0:
                continue
    
            # Inode numbers are only unique within one filesystem device (`st_dev`).
            inode_key = (info.st_dev, info.st_ino)
            if inode_key not in best_by_inode or path < best_by_inode[inode_key][0]:
                best_by_inode[inode_key] = (path, info.st_size, info.st_mtime_ns)
    
        # files: {path: (size_bytes, mtime_ns)}
        files: Dict[str, Tuple[int, int]] = {}
        for best_path, size_bytes, mtime_ns in best_by_inode.values():
            files[best_path] = (size_bytes, mtime_ns)
        return files
    
  5. Stream SHA-256 digests and split candidate groups

    Never call f.read() with no size argument on user files: a single 50 GB raw video would exhaust RAM. Instead, file_digest reads in fixed 1 MiB (CHUNK_BYTES) blocks so memory usage stays constant regardless of file size. Passing limit = 4096 hashes at most the first 4 KiB; passing limit = -1 hashes until end-of-file.

    Inside each candidate group, group_by_signature builds a dictionary by_digest (sha256_hex -> [paths]) and discards every bucket of length 1:

    from typing import Dict, List
    import hashlib
    
    PARTIAL_BYTES = 4096
    CHUNK_BYTES = 1 << 20
    
    
    def file_digest(path: str, limit: int = -1) -> str:
        hasher = hashlib.sha256()
        remaining = limit
        with open(path, "rb") as f:
            # Stop when `remaining` reaches 0; when `limit < 0`, read until EOF.
            while remaining != 0:
                read_size = CHUNK_BYTES if remaining < 0 else min(CHUNK_BYTES, remaining)
                block = f.read(read_size)
                if not block:
                    break
                hasher.update(block)
                if remaining > 0:
                    remaining -= len(block)
        return hasher.hexdigest()
    
    
    def group_by_signature(groups: List[List[str]], limit: int) -> List[List[str]]:
        surviving_groups: List[List[str]] = []
    
        for group in groups:
            # by_digest: {sha256_hex: [path_1, path_2, ...]} within one prior bucket
            by_digest: Dict[str, List[str]] = {}
            for path in group:
                try:
                    digest = file_digest(path, limit)
                except OSError:
                    continue
                if digest not in by_digest:
                    by_digest[digest] = []
                by_digest[digest].append(path)
    
            # Any bucket of size 1 has a unique signature and cannot have a duplicate.
            for matching_paths in by_digest.values():
                if len(matching_paths) >= 2:
                    surviving_groups.append(matching_paths)
    
        return surviving_groups
    
  6. Pick the canonical keeper and verify byte-for-byte

    Why use SHA-256 instead of MD5 or SHA-1, and why still compare bytes afterward?

    • Cryptographic collision resistance: MD5 and SHA-1 have published collision attacks where two distinct files share the exact same digest. An attacker (or test file repository) containing a crafted colliding pair could trick an unverified MD5 deduplicator into deleting unique data. SHA-256 has 256 output bits and no known collision attacks.
    • Defense in depth before irreversible deletion: Comparing candidate files byte-by-byte against the chosen keeper guarantees zero false positives even if a file changed on disk mid-scan or if a theoretical hash collision ever occurred.

    By sorting a group's (mtime_ns, path) tuples first, the canonical copy comes first. Keeping a keepers list (almost always length 1, and only growing if a candidate's bytes differ from existing keepers) handles even a hypothetical hash collision cleanly without losing any duplicate group:

    from typing import Dict, List, Set, Tuple
    
    CHUNK_BYTES = 1 << 20
    
    
    def same_bytes(path_a: str, path_b: str) -> bool:
        with open(path_a, "rb") as fa, open(path_b, "rb") as fb:
            while True:
                block_a = fa.read(CHUNK_BYTES)
                block_b = fb.read(CHUNK_BYTES)
                if block_a != block_b:
                    return False
                # Because `block_a == block_b`, an empty `block_a` means both hit EOF together.
                if not block_a:
                    return True
    
    
    def collect_verified_duplicates(
        group: List[str], files: Dict[str, Tuple[int, int]]
    ) -> Set[str]:
        candidates: List[Tuple[int, str]] = []
        for path in group:
            mtime_ns = files[path][1]
            candidates.append((mtime_ns, path))
        candidates.sort()
    
        # `keepers` holds one canonical path per distinct byte content.
        keepers: List[str] = []
        duplicates: Set[str] = set()
    
        for _, path in candidates:
            try:
                matched_existing_keeper = False
                for keep_path in keepers:
                    if same_bytes(keep_path, path):
                        duplicates.add(path)
                        matched_existing_keeper = True
                        break
                if not matched_existing_keeper:
                    keepers.append(path)
            except OSError:
                continue
    
        return duplicates
    

    In production, the caller executing the deletion plan should also default to --dry-run, re-verify lstat (size, mtime_ns) immediately before unlinking to close time-of-check/time-of-use windows, and move files to a same-filesystem quarantine/trash folder before permanent removal.

  7. Walk through Sample 1

    Trace five candidate paths (the four PDFs from Example 1 plus an empty .lock file) through every stage:

    Input path                     Size     mtime   Bytes                Stage 0 result
    -----------------------------------------------------------------------------------
    2021/report.pdf                1200 B   100s    "Q1-summary" * 120   kept
    downloads/report_copy.pdf      1200 B   250s    "Q1-summary" * 120   kept
    export/doc_01.pdf              1200 B   100s    "Q1-summary" * 120   kept
    2022/report.pdf                1200 B    90s    "Q2-summary" * 120   kept
    empty_a.lock                      0 B   100s    ""                   skipped (0 bytes)
    
    Stage 1 (by size):
      1200 B -> [2021/report.pdf, downloads/report_copy.pdf, export/doc_01.pdf, 2022/report.pdf]
    
    Stage 2 (4 KiB SHA-256):
      sha256("Q1-summary"*120) -> [2021/report.pdf, downloads/report_copy.pdf, export/doc_01.pdf] (len 3 -> survives)
      sha256("Q2-summary"*120) -> [2022/report.pdf]                                               (len 1 -> dropped)
    
    Stage 3 (full SHA-256):
      1200 B <= 4096 B -> already fully hashed in Stage 2, no extra disk read needed!
    
    Stage 4 (sort by (mtime_ns, path) + byte check):
      sorted = [
        (100s, "2021/report.pdf"),
        (100s, "export/doc_01.pdf"),
        (250s, "downloads/report_copy.pdf"),
      ]
      keeper = "2021/report.pdf"
      verified duplicates = {"export/doc_01.pdf", "downloads/report_copy.pdf"}
    

    Notice that 2021/report.pdf and 2022/report.pdf share the exact same filename report.pdf and 1,200-byte size, yet their byte sequences differ so 2022/report.pdf is never marked as a duplicate — filenames only break timestamp ties among verified byte-identical files.

  8. Complete solution

    from typing import Dict, List, Set, Tuple
    import hashlib
    import os
    import stat
    
    # Read only the first 4 KiB during Stage 2 to eliminate non-duplicates cheaply.
    PARTIAL_BYTES = 4096
    
    # Stream files in 1 MiB blocks so memory stays O(1) even on huge video files.
    CHUNK_BYTES = 1 << 20
    
    
    def file_digest(path: str, limit: int = -1) -> str:
        """Return the hex SHA-256 of the first `limit` bytes (or full file when limit < 0)."""
        hasher = hashlib.sha256()
        remaining = limit
        with open(path, "rb") as f:
            # Stop when `remaining` reaches 0; when `limit < 0`, read until EOF.
            while remaining != 0:
                read_size = CHUNK_BYTES if remaining < 0 else min(CHUNK_BYTES, remaining)
                block = f.read(read_size)
                if not block:
                    break
                hasher.update(block)
                if remaining > 0:
                    remaining -= len(block)
        return hasher.hexdigest()
    
    
    def same_bytes(path_a: str, path_b: str) -> bool:
        """Stream two equal-sized files side by side and verify every byte matches."""
        with open(path_a, "rb") as fa, open(path_b, "rb") as fb:
            while True:
                block_a = fa.read(CHUNK_BYTES)
                block_b = fb.read(CHUNK_BYTES)
                if block_a != block_b:
                    return False
                # Because `block_a == block_b`, an empty `block_a` means both hit EOF together.
                if not block_a:
                    return True
    
    
    def collect_files(paths: List[str]) -> Dict[str, Tuple[int, int]]:
        """Map one canonical path per usable disk inode to `(size_bytes, mtime_ns)`.
    
        Skips missing/unreadable paths, symlinks, non-regular files, and empty files.
        When multiple paths point to the same `(st_dev, st_ino)` inode (duplicate path
        strings or hard links), keeps the lexicographically smallest path so results do
        not depend on input order.
        """
        # best_by_inode: {(st_dev, st_ino): (smallest_path, size_bytes, mtime_ns)}
        best_by_inode: Dict[Tuple[int, int], Tuple[str, int, int]] = {}
    
        for path in paths:
            try:
                # Use lstat so symlinks are inspected as links rather than followed.
                info = os.lstat(path)
            except OSError:
                continue
    
            # Ignore directories, sockets, devices, symlinks, and 0-byte marker files.
            if not stat.S_ISREG(info.st_mode) or info.st_size == 0:
                continue
    
            # Inode numbers are only unique within one filesystem device (`st_dev`).
            inode_key = (info.st_dev, info.st_ino)
            if inode_key not in best_by_inode or path < best_by_inode[inode_key][0]:
                best_by_inode[inode_key] = (path, info.st_size, info.st_mtime_ns)
    
        # files: {path: (size_bytes, mtime_ns)}
        files: Dict[str, Tuple[int, int]] = {}
        for best_path, size_bytes, mtime_ns in best_by_inode.values():
            files[best_path] = (size_bytes, mtime_ns)
        return files
    
    
    def group_by_signature(groups: List[List[str]], limit: int) -> List[List[str]]:
        """Split each candidate group by SHA-256 of its first `limit` bytes; keep groups of 2+."""
        surviving_groups: List[List[str]] = []
    
        for group in groups:
            # by_digest: {sha256_hex: [path_1, path_2, ...]} within one prior bucket
            by_digest: Dict[str, List[str]] = {}
            for path in group:
                try:
                    digest = file_digest(path, limit)
                except OSError:
                    continue
                if digest not in by_digest:
                    by_digest[digest] = []
                by_digest[digest].append(path)
    
            # Any bucket of size 1 has a unique signature and cannot have a duplicate.
            for matching_paths in by_digest.values():
                if len(matching_paths) >= 2:
                    surviving_groups.append(matching_paths)
    
        return surviving_groups
    
    
    def collect_verified_duplicates(
        group: List[str], files: Dict[str, Tuple[int, int]]
    ) -> Set[str]:
        """Keep the oldest copy (ties broken by smallest path) and byte-verify all duplicates."""
        # Sort `(mtime_ns, path)` tuples so the canonical keeper always comes first.
        candidates: List[Tuple[int, str]] = []
        for path in group:
            mtime_ns = files[path][1]
            candidates.append((mtime_ns, path))
        candidates.sort()
    
        # `keepers` holds one canonical path per distinct byte content (handles hash collisions).
        keepers: List[str] = []
        duplicates: Set[str] = set()
    
        for _, path in candidates:
            try:
                matched_existing_keeper = False
                for keep_path in keepers:
                    if same_bytes(keep_path, path):
                        duplicates.add(path)
                        matched_existing_keeper = True
                        break
                if not matched_existing_keeper:
                    keepers.append(path)
            except OSError:
                # Never delete a file if either file disappeared or became unreadable mid-check.
                continue
    
        return duplicates
    
    
    def find_deletable_duplicates(paths: List[str]) -> Set[str]:
        """Return the set of file paths that are verified byte-identical duplicates.
    
        Exactly one canonical copy of every byte-identical group is kept (oldest mtime,
        then smallest path), so deleting the returned set never loses unique data.
        """
        files = collect_files(paths)
    
        # Stage 1: Group by exact byte size; unique sizes never touch file contents on disk.
        by_size: Dict[int, List[str]] = {}
        for path, (size_bytes, _) in files.items():
            if size_bytes not in by_size:
                by_size[size_bytes] = []
            by_size[size_bytes].append(path)
    
        size_groups: List[List[str]] = []
        for same_size_paths in by_size.values():
            if len(same_size_paths) >= 2:
                size_groups.append(same_size_paths)
    
        # Stage 2: Split same-size groups by the SHA-256 of their first 4 KiB.
        partial_groups = group_by_signature(size_groups, PARTIAL_BYTES)
    
        # Stage 3: Hash the full file only when file size exceeds 4 KiB (smaller files
        # were already hashed end-to-end in Stage 2).
        small_groups: List[List[str]] = []
        large_groups: List[List[str]] = []
        for group in partial_groups:
            group_size = files[group[0]][0]
            if group_size <= PARTIAL_BYTES:
                small_groups.append(group)
            else:
                large_groups.append(group)
    
        full_hash_groups = small_groups + group_by_signature(large_groups, -1)
    
        # Stage 4: Choose canonical keepers and verify every duplicate byte by byte.
        to_delete: Set[str] = set()
        for group in full_hash_groups:
            to_delete.update(collect_verified_duplicates(group, files))
    
        return to_delete
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine sorting a warehouse of two million mystery books to pull out exact duplicate printings. You would never read every book cover to cover right away: first you stack books by exact page count written on the spine, toss aside every single-book stack, open only the first page of books that share a page count, and read every word only when two books match on both page count and page one. That progressive filter is our signature funnel:

  1. Metadata filter (lstat + size): An inode (the operating system's unique record for one physical file on a disk device, identified by (st_dev, st_ino)) lets us ignore duplicate paths to the same underlying file, while symbolic links (pointer files that redirect to another path) and 0-byte files are skipped. Grouping by file size in an in-memory dictionary eliminates every uniquely sized file with zero content reads.
  2. Partial hash (4 KiB SHA-256): A cryptographic hash (a deterministic math function like SHA-256 that maps arbitrary bytes to a fixed 256-bit fingerprint where even a 1-bit change scrambles the output) separates almost all same-sized non-duplicates after reading just 4,096 bytes.
  3. Full streamed hash + byte verification: Only surviving groups larger than 4 KiB are hashed end-to-end using streaming I/O (reading fixed 1 MiB chunks in a loop so RAM stays flat regardless of file size). Finally, each group is sorted by (mtime_ns, path) so the oldest copy survives, and every duplicate is compared byte-by-byte against that canonical keeper to guard against a hash collision (two different inputs producing the same hash) or mid-scan file edits.

Why do simpler approaches fail? Comparing every pair of files directly requires O(N^2) reads — around two trillion comparisons for two million files. Hashing every file end-to-end up front is O(N) in file count, but reads every single byte on an 8 TB drive (~11 hours at 200 MB/s), wasting disk bandwidth on the vast majority of files whose byte size is already unique.

Here is a tiny 4-file trace:

Files:
  2021/report.pdf     (8000 B, t=100, prefix="PDF1...", tail="...X")
  export/doc_01.pdf   (8000 B, t=200, prefix="PDF1...", tail="...X")
  2022/report.pdf     (8000 B, t=150, prefix="PDF1...", tail="...Y")
  summary.txt         (5120 B, t=90,  unique size)

Stage 1 (size):       summary.txt dropped immediately; the three 8000 B PDFs remain.
Stage 2 (first 4 KiB): all three PDFs share prefix "PDF1...", so all three survive.
Stage 3 (full hash):  2022/report.pdf differs in tail -> dropped; 2021/report.pdf and export/doc_01.pdf match.
Stage 4 (verify):     2021/report.pdf kept (oldest, t=100); export/doc_01.pdf matches byte-for-byte -> delete {"export/doc_01.pdf"}.

Complexity

Let N be the number of input paths and B be the total bytes across all candidate files.

  • Time: O(N + B) worst-case, and proportional only to colliding files in practice. Stage 0 and Stage 1 perform one os.lstat system call and O(1) average hash-table work per path. Stage 2 reads at most 4 KiB per file whose byte size is shared. Stage 3 streams full bytes once only for files larger than 4 KiB whose size and 4 KiB prefix collided. Stage 4 sorts tiny duplicate groups of size k in O(k log k) and streams each duplicate copy alongside its canonical keeper once (<= 2x duplicate bytes when there are no hash collisions).
  • Space: O(N) for metadata, O(1) for file content buffers. We store at most N path strings, (st_dev, st_ino) pairs, (size, mtime_ns) tuples, and hex digest keys in memory (roughly 0.8–1.0 GB for 2,000,000 paths in CPython), while file_digest and same_bytes hold at most two 1 MiB buffers in RAM even for a 50 GB video.
  • Disk I/O considerations: On spinning hard disks (HDDs), Stage 2 is seek-bound (~100–150 random 4 KiB reads per second), so sorting reads by inode number often reduces head movement; Stages 3 and 4 are sequential-bandwidth-bound. On NVMe SSDs, random reads are cheap and CPython's hashlib releases the Global Interpreter Lock (GIL) on buffers over 2 KiB, so a bounded thread pool speeds up Stages 2 and 3 substantially.

Edge cases

  • Repeated paths, "a/./pic.jpg" vs "a/pic.jpg", and hard links: A hard link is an extra directory filename pointing to the exact same (st_dev, st_ino) inode. Without inode deduplication, passing two spellings of one path tricks the program into deleting the only copy on disk; deduplicating by (st_dev, st_ino) and keeping the smallest path per inode avoids data loss and keeps tie-breaking independent of input order.
  • Symbolic links: Calling os.stat follows symlinks, which could keep a symlink aaa_shortcut.bin and report its target master.bin as deletable, breaking the link and destroying the data. os.lstat inspects the link itself so symlinks are skipped safely.
  • Identical names with different bytes (2021/report.pdf vs 2022/report.pdf): Never treated as duplicates because filenames only break ties after byte equality is proven.
  • Identical bytes with different permissions or timestamps: Treated as duplicates; modification time only chooses which copy survives.
  • Files <= 4 KiB: Stage 2 already hashes their entire content, so Stage 3 skips re-reading them before Stage 4 verifies bytes.
  • Empty (0-byte) files: All empty files are trivially byte-equal, but they are typically application placeholders (.init, .nomedia), so skipping st_size == 0 avoids breaking directory structures.
  • Files modified or deleted mid-scan: Any OSError or byte mismatch causes the path to be skipped rather than added to to_delete, failing safe.

Common mistakes

  • Reading whole files into RAM with f.read(): Works on small unit tests and crashes with MemoryError on the first large raw image archive or video file.
  • Hashing every file completely before grouping by size: Correct output, 5–10x slower wall-clock time because unique-sized files still pay full disk read bandwidth.
  • Using os.stat instead of os.lstat or ignoring (st_dev, st_ino): Causes catastrophic data loss on symlinks and duplicate path strings.
  • Relying on MD5/SHA-1 without byte verification: Vulnerable to crafted hash collisions; even with SHA-256, streaming same_bytes before deletion protects against mid-scan file mutations and bugs.
  • Non-deterministic keeper selection: Taking next(iter(group_set)) picks a random survivor across Python runs due to hash randomization (PYTHONHASHSEED), making dry-run reviews unreliable.

Alternative approaches

  • Incremental single-pass dictionary (signature -> canonical_path): Maintain size buckets lazily so the first file of size S stores only its path, and only when a second file of size S arrives do you compute 4 KiB and full hashes for that first file. This fits long-running background deduplication daemons well.
  • First-and-last 4 KiB partial signature: Formats with boilerplate headers (like container formats or camera RAW headers) often match in the first 4 KiB; hashing both the first 4 KiB and last 4 KiB filters out more non-duplicates before Stage 3 at the cost of one extra seek.
  • Hard-linking or reflinking instead of unlinking: Replacing duplicate copies with copy-on-write reflinks (supported on APFS, Btrfs, and XFS, where two paths share disk blocks until one is edited) reclaims disk space without breaking scripts or albums that still reference the duplicate path.

Follow-up questions

  • How would you adapt this scan to run incrementally on a directory tree that receives new files every day? Store a local SQLite catalog (path, dev, ino, size, mtime_ns, ctime_ns, sha256) indexed on (size, sha256). On subsequent runs, skip re-hashing any file whose (dev, ino, size, mtime_ns, ctime_ns) matches the catalog — checking ctime_ns (inode change time) matters because file importers often backdate mtime_ns to an archive creation date while the OS always updates ctime_ns on write. New or changed files only trigger disk reads when their size already exists in the catalog.
  • What if there are hundreds of millions of files and the in-memory metadata dictionary no longer fits in RAM? Stream (size_bytes, mtime_ns, dev, ino, path) records to disk and run an external merge sort (sorting fixed-RAM chunks and merging sorted runs from disk, or inserting into an on-disk SQLite table indexed by (dev, ino) then size_bytes). Once sorted by size_bytes, a sequential scan holds only one size bucket in RAM at a time while running Stages 2–4 unchanged.
  • How do your deduplication rules change on a shared multi-user machine where different users own identical copies? Deleting Bob's file because Alice has an older unreadable-to-Bob copy breaks Bob's access! Either include ownership and permissions (st_uid, st_gid, mode) in the Stage 1 grouping key so deduplication happens strictly within one user's files, or deduplicate storage transparently underneath using filesystem-level copy-on-write reflinks so both users keep independent file handles and permissions.

Follow-up questions

Similar questions

More Abnormal Security interview questions

All 2 Abnormal Security questions →