Exact Command-Line Line Deduplication Beyond Available RAM

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Prompt

Architect a command-line utility that removes duplicate lines from a massive input file when the set of unique lines is far larger than available RAM. Walk through how your design coordinates disk-backed intermediate files and how the caller's ordering contract changes the pipeline.

Two lines count as duplicates only when their full byte contents match (100% exactness—probabilistic filters that can drop unseen lines are off-limits unless a user explicitly opts into lossy behavior). Because key operational limits are left open, state the clarifying questions and assumptions you would establish first around output ordering (first-seen order vs. lexicographically sorted vs. arbitrary order), RAM and scratch-disk ceilings, pathologically long individual lines, and crash/resume behavior.

Scope & Expectations

  • Contract & sizing: Pin down byte-level line equality, newline boundary behavior, memory vs. scratch-storage budgets, single-line size bounds, and recovery semantics before choosing an algorithm.
  • External-memory strategies: Contrast disk-backed external merge sort against deterministic hash bucketing, quantifying sequential I/O passes and in-memory hash-table overhead.
  • Order preservation: Show how to retain exact first-seen line order across disk partitions or runs without holding all surviving lines in memory at once.
  • Exactness & operational edge cases: Explain why fixed-width fingerprint sets violate strict uniqueness at billion-line scale, and handle oversized single lines, tight scratch space, and idempotent restarts.

Step-by-step walkthrough

  1. Clarify the contract and size the problem

    Before picking an algorithm, pin down what "duplicate", "exact", and "output order" mean, because each answer changes the design:

    • Byte-exact equality: Compare raw UTF-8/byte sequences (bytes), never decoded locale strings, so character-encoding quirks or locale sorting rules cannot merge distinct lines. Treat \n solely as a line separator ("abc\n" at line 1 and "abc" at the end of the file without a trailing newline are the same line "abc").
    • Output order (the main design fork): May the output appear in sorted order, in arbitrary order, or must every kept line stay in first-occurrence order (appearing in the exact sequence in which each unique line was first seen)?
    • Resource envelope: How much RAM and temporary disk space do we have? Can a single pathological line exceed RAM? Must an interrupted run resume from a checkpoint?
    • Strict exactness: Do not substitute a probabilistic filter (such as a Bloom filter or 64-bit hash-only set) unless the caller explicitly accepts silent data loss.

    Let us anchor every calculation on one concrete running scenario:

    Input file:       200 GB total, 4 billion lines, average 50 bytes per line
    Distinct lines:   1.5 billion unique lines (~75 GB of raw unique text)
    Machine budget:   8 GB RAM total -> 6 GB usable working memory
    SSD throughput:   ~500 MB/s sequential read or write
    

    An ordinary in-memory set stores every unique line at once. Even with zero data-structure overhead, 75 GB of distinct text cannot fit in 6 GB of RAM:

    def dedup_in_memory(input_path: str, output_path: str) -> None:
        """Exact and preserves first-occurrence order, but crashes when unique lines > RAM."""
        seen = set()
        with open(input_path, "rb") as src, open(output_path, "wb") as out:
            for raw_line in src:
                # Strip only the single trailing newline terminator, keeping all content bytes.
                line = raw_line.removesuffix(b"\n")
                if line not in seen:
                    seen.add(line)
                    out.write(line + b"\n")
    
  2. Core insight: make equal lines meet in small chunks

    Since we cannot hold all unique lines in RAM simultaneously, any exact external-memory design must rearrange the file on disk so that all copies of the same line are guaranteed to meet inside a chunk that fits in 6 GB of RAM. There are two classic ways to make equal items meet:

    Strategy A — External Merge Sort (brings equal lines together by ORDER):
      [200 GB input] --> 45 sorted 4.5 GB run files --> 45-way streaming merge --> [sorted unique output]
                         (adjacent duplicates dropped)   (adjacent duplicates dropped)
    
    Strategy B — Hash Partitioning (brings equal lines together by BUCKET):
      [200 GB input] --> hash(line) % 32 --> 32 bucket files --> dedup 1 bucket at a time in a 6 GB RAM set
                         (identical lines always land in the same bucket!)
    

    Both strategies stream sequentially from disk—avoiding random disk seeks, which are orders of magnitude slower—and both compare full byte strings so zero unique lines are ever lost.

  3. Option 1: external merge sort when sorted output is allowed

    When sorted output is acceptable, external merge sort (an algorithm that sorts data larger than RAM by sorting fixed-size chunks in memory and merging those sorted files together) solves deduplication cleanly:

    1. Run generation: Read lines until our 6 GB working budget fills up, sort the batch in memory, drop adjacent duplicates right away, and write the result to disk as a sorted temporary file called a run. Because each in-memory line also needs a pointer and length (~16 bytes of metadata beside 50 bytes of text in C), a 6 GB budget holds roughly 6 GB * (50 / 66) = 4.5 GB of raw text per run, producing 200 GB / 4.5 GB ≈ 45 run files.
    2. k-way merge: Open all 45 sorted runs at once with a 100 MB sequential read buffer per run (45 * 100 MB = 4.5 GB, comfortably inside 6 GB RAM). Use a min-heap (a priority queue that pops the smallest current line across all 45 runs in O(log 45) time) and write each line only if it differs from previous_line.
    Run 0:  "alpha" -> "gamma" -> ...  \
    Run 1:  "alpha" -> "beta"  -> ...   +--> Min-heap pops: "alpha", "alpha" (skip!), "beta", "gamma"
    Run 2:  "beta"  -> "delta" -> ...  /
    

    I/O cost: In the worst case (few duplicates inside individual runs), we read 200 GB, write 200 GB of runs, read 200 GB of runs back, and write 75 GB of unique output = 675 GB of sequential I/O, or 675,000 MB / 500 MB/s ≈ 22.5 minutes. On Unix, LC_ALL=C sort -u -S 6G -T /tmp/runs input.txt > output.txt implements this directly (LC_ALL=C forces byte-exact comparison instead of locale collation rules that can treat distinct byte strings as equal).

    import heapq
    import os
    
    
    def _write_sorted_run(batch: list[bytes], tmp_dir: str, run_id: int) -> str:
        batch.sort()
        run_path = os.path.join(tmp_dir, f"run_{run_id:04d}.bin")
        previous = None
        with open(run_path, "wb") as out:
            for line in batch:
                if line != previous:
                    out.write(line + b"\n")
                    previous = line
        return run_path
    
    
    def create_sorted_runs(input_path: str, tmp_dir: str, max_run_bytes: int) -> list[str]:
        run_paths = []
        batch = []
        batch_bytes = 0
        with open(input_path, "rb") as src:
            for raw_line in src:
                line = raw_line.removesuffix(b"\n")
                batch.append(line)
                batch_bytes += len(raw_line)
                if batch_bytes >= max_run_bytes:
                    run_paths.append(_write_sorted_run(batch, tmp_dir, len(run_paths)))
                    batch = []
                    batch_bytes = 0
        if batch:
            run_paths.append(_write_sorted_run(batch, tmp_dir, len(run_paths)))
        return run_paths
    
    
    def _iter_lines(path: str):
        with open(path, "rb") as src:
            for raw_line in src:
                yield raw_line.removesuffix(b"\n")
    
    
    def merge_runs_unique(run_paths: list[str], output_path: str) -> None:
        previous = None
        streams = [_iter_lines(path) for path in run_paths]
        with open(output_path, "wb") as out:
            for line in heapq.merge(*streams):
                if line != previous:
                    out.write(line + b"\n")
                    previous = line
    
  4. Option 2: hash partitioning when any output order is allowed

    Sorting spends O(N log N) CPU comparisons ordering different lines relative to each other, even though deduplication only needs identical lines to meet. Hash partitioning (splitting a dataset into P bucket files using hash(item) % P) avoids sorting altogether:

    1. Partition pass (O(N)): Stream the input once. For each line, compute a deterministic hash h and append the line to bucket file h % P. Because equal byte strings always produce the exact same hash, every copy of line X lands in the same bucket file.
    2. Per-bucket deduplication (O(N)): Each bucket holds roughly 1 / P of the distinct lines (duplicates do not grow the in-memory set!). Load one bucket file at a time into a fresh in-memory set, emit each first-seen line to the final output, clear the set, and delete that bucket file.

    How to size P: Raw distinct text is 75 GB, but hash tables have per-entry overhead. In 64-bit CPython, a 49-byte bytes object plus its set slot costs ~115 bytes (~2.3x raw text, or ~173 GB across 1.5B distinct lines). Dividing 173 GB by our 6 GB budget gives 29 buckets; rounding up to P = 32 puts ~2.34 GB of raw distinct text (~5.4 GB in a CPython set, or ~3.5 GB in a compact C/Rust hash table) per bucket. Always use a deterministic hash like hashlib.blake2b—Python's built-in hash() randomizes its seed on every process startup, which breaks crash recovery.

    import hashlib
    import os
    
    
    def bucket_index(line: bytes, num_buckets: int, seed: bytes = b"") -> int:
        """Deterministic bucket routing across processes, unlike Python's randomized hash()."""
        digest = hashlib.blake2b(line, digest_size=8, key=seed).digest()
        return int.from_bytes(digest, "big") % num_buckets
    
    
    def dedup_unordered_partitions(input_path: str, tmp_dir: str, output_path: str, num_buckets: int) -> None:
        bucket_paths = [os.path.join(tmp_dir, f"bucket_{i:04d}.bin") for i in range(num_buckets)]
        writers = []
        try:
            for path in bucket_paths:
                writers.append(open(path, "wb"))
            with open(input_path, "rb") as src:
                for raw_line in src:
                    line = raw_line.removesuffix(b"\n")
                    writers[bucket_index(line, num_buckets)].write(line + b"\n")
        finally:
            for writer in writers:
                writer.close()
    
        with open(output_path, "wb") as out:
            for path in bucket_paths:
                seen = set()
                with open(path, "rb") as bucket_file:
                    for raw_line in bucket_file:
                        line = raw_line.removesuffix(b"\n")
                        if line not in seen:
                            seen.add(line)
                            out.write(line + b"\n")
                os.remove(path)
    
  5. Preserving first-occurrence order with line numbers

    What if the output must keep every unique line in the exact order it first appeared? Attach a 0-based line number (line_number, line) during the very first read pass before anything moves lines out of order!

    Look at how clean this is with hash partitioning: 1. Because Pass 1 scans the input from top to bottom (0, 1, 2, ...), every bucket file receives records in strictly increasing line_number order. 2. When Pass 2 deduplicates each bucket sequentially, the first copy of any line it encounters is guaranteed to have the smallest line_number, and the surviving (line_number, line) records written to kept_i remain already sorted by line_number! 3. A single P-way streaming merge by line_number across kept_0 ... kept_{P-1} restores the exact global first-occurrence order—with zero sorting passes!

    Input lines (idx: text):   0:"b"   1:"a"   2:"b"   3:"c"   4:"a"
      |
      +-- Bucket 0 ("a", "c"):  1:"a", 3:"c", 4:"a"  --dedup-->  kept_0: [1:"a", 3:"c"]  (sorted by idx!)
      +-- Bucket 1 ("b"):       0:"b", 2:"b"         --dedup-->  kept_1: [0:"b"]         (sorted by idx!)
                                                                     |
      2-way merge by idx across kept_0 and kept_1:  0:"b", 1:"a", 3:"c"  -->  Output: b, a, c
    

    By contrast, preserving first-occurrence order with external merge sort requires two full external sorts: first sort (line, line_number) to keep the smallest line_number per distinct line, then run a second external sort on those 1.5 billion survivors ordered by line_number. Carrying 8-byte binary line numbers across 4 billion lines adds 32 GB of temporary disk data (~43 GB if formatted as ASCII digits plus \t), raising total sequential I/O for hash partitioning + k-way merge from 675 GB to roughly 950 GB.

    import heapq
    import os
    
    
    def split_numbered_partitions(input_path: str, tmp_dir: str, num_buckets: int) -> list[str]:
        bucket_paths = [os.path.join(tmp_dir, f"part_{i:04d}.bin") for i in range(num_buckets)]
        writers = []
        try:
            for path in bucket_paths:
                writers.append(open(path, "wb"))
            with open(input_path, "rb") as src:
                for line_num, raw_line in enumerate(src):
                    line = raw_line.removesuffix(b"\n")
                    target = bucket_index(line, num_buckets)
                    writers[target].write(f"{line_num}\t".encode("ascii") + line + b"\n")
        finally:
            for writer in writers:
                writer.close()
        return bucket_paths
    
    
    def dedup_numbered_bucket(part_path: str, kept_path: str) -> None:
        seen = set()
        with open(part_path, "rb") as src, open(kept_path, "wb") as out:
            for record in src:
                # Split only on the first tab so tabs inside the line content stay intact.
                _, line = record.removesuffix(b"\n").split(b"\t", 1)
                if line not in seen:
                    seen.add(line)
                    out.write(record)
    
    
    def _iter_numbered(path: str):
        with open(path, "rb") as src:
            for record in src:
                num_bytes, line = record.removesuffix(b"\n").split(b"\t", 1)
                yield int(num_bytes), line
    
    
    def merge_in_first_occurrence_order(kept_paths: list[str], output_path: str) -> None:
        streams = [_iter_numbered(path) for path in kept_paths]
        with open(output_path, "wb") as out:
            # Every line_num is unique, so heapq.merge never compares line bytes.
            for _, line in heapq.merge(*streams):
                out.write(line + b"\n")
    
  6. Why hash-only shortcuts fail the exactness requirement

    Notice the critical distinction in Option 2: we use a hash only to pick a bucket file, and inside each bucket line not in seen compares the entire byte sequence on any hash match.

    Why not avoid disk partitioning by keeping an in-memory set of 64-bit hashes (8 bytes per unique line)? Two reasons: 1. Even 64-bit hashes exceed RAM here: 1.5 billion * 8 bytes = 12 GB of raw hashes before hash-table slot overhead—already twice our 6 GB limit. 2. Silent data loss from the birthday paradox: The birthday paradox is the probability phenomenon where collisions among n random draws from M possibilities become likely around sqrt(M) items, long before M. With M = 2^64 ≈ 1.84 * 10^19 possible 64-bit hashes and n = 1.5 * 10^9 distinct lines, the number of distinct pairs is n * (n - 1) / 2 ≈ 1.125 * 10^18:

    Expected hash collisions   = n^2 / (2 * 2^64) = 2.25e18 / 3.69e19 ≈ 0.061
    Chance of >= 1 lost line   = 1 - exp(-0.061) ≈ 5.9% (~1 in 17 runs silently drops data!)
    

    Even a 128-bit cryptographic hash (SHA-256 truncated to 128 bits, collision probability ~3 * 10^-21 at 1.5B lines) still is not mathematically exact—and 1.5B * 16 bytes = 24 GB still overflows 6 GB RAM anyway. Partitioning full lines to disk gives 100% mathematical exactness within bounded memory.

  7. Disk budgets, giant lines, restarts, and CLI assembly

    To finish a production-grade CLI design, address the three operational edge cases from the prompt:

    • Tight temporary disk space: Partitioning needs ~200–243 GB of temp disk (deleting each part_i right after writing kept_i). If temp disk is nearly zero and any output order is allowed, trade disk writes for sequential reads: run P = 32 passes over the input file, keeping an in-memory set only for lines where hash(line) % 32 == pass_id (0 bytes of temporary disk, at the cost of reading 200 GB * 32 = 6.4 TB, ~3.5 hours at 500 MB/s).
    • Single line larger than 6 GB RAM: Stream input in fixed 1 MB chunks instead of readline(). If a line crosses a size threshold (say 64 MB), feed its chunks incrementally into blake2b without buffering the whole line in RAM, and store (digest, file_offset, byte_length) as a proxy record. Only if two giant lines share both byte_length and digest do we open two file cursors at their file_offsets and compare 1 MB chunks side by side.
    • Crash recovery / restarts: Write each completed stage (part_0..31, each kept_i, final output) to a .tmp file, call fsync (an OS call that forces buffered file data onto physical storage before returning), atomically os.replace() it to its final name, and log the stage in a tiny manifest.json. Because blake2b routing is deterministic, a restarted job skips finished buckets and re-runs only the interrupted stage.
    CLI summary:
      dedup-exact --order [first|sorted|any] --memory 6G --tmp-dir /scratch input.log > unique.log
    
      - Fits in RAM?          -> single-pass in-memory set (preserves first-occurrence order)
      - --order sorted        -> external merge sort (45 runs + 45-way merge, ~675 GB seq I/O)
      - --order any           -> 32-way blake2b hash buckets + per-bucket set (~675 GB seq I/O, O(N) CPU)
      - --order first         -> numbered 32-way hash buckets + per-bucket set + 32-way merge (~950 GB seq I/O)
    

Intuition & how it works

Imagine you are handed 4 billion paper slips (200 GB) and asked to throw away duplicates while sitting at a tiny desk that can only hold a small stack (6 GB RAM) at once. You cannot spread every unique slip across your desk at the same time (75 GB of unique slips), and walking back and forth to search random filing cabinets on disk would take days. Instead, you place 32 mail bins on the floor and sort slips into bins using a deterministic rule (hash(text) % 32). Because two identical slips always land in the exact same mail bin, no duplicate can hide in another bin—and each individual bin holds only ~1/32 of the unique slips, which easily fits on your desk one bin at a time!

The obvious in-memory set crashes with MemoryError as soon as distinct lines exceed RAM, while Unix sort -u (which uses external merge sort, sorting fixed-size memory chunks to disk and merging them) scrambles the original line order and does O(N log N) string comparisons. If the caller needs first-occurrence order preserved, stamping each line with its 0-based line number during the initial pass lets us deduplicate each mail bin independently and then zip the 32 already-ordered bin outputs back together in one streaming pass.

Here is a 5-line trace (b, a, b, c, a) across 2 hash bins when preserving first-occurrence order:

1. Number & route (1 sequential scan):
   0:"b" -> bin 1 | 1:"a" -> bin 0 | 2:"b" -> bin 1 | 3:"c" -> bin 0 | 4:"a" -> bin 0

2. Deduplicate each bin in RAM (keeps earliest copy; line numbers stay sorted!):
   bin 0: [1:"a", 3:"c", 4:"a"]  -->  kept_0: [1:"a", 3:"c"]
   bin 1: [0:"b", 2:"b"]         -->  kept_1: [0:"b"]

3. 2-way min-heap merge ordered by line number:
   merge([1:"a", 3:"c"], [0:"b"]) --> 0:"b", 1:"a", 3:"c"  -->  Output: b, a, c

Key points

  • Clarify the contract first: Confirm byte-exact equality (and missing-final-newline handling), whether output order must be first-occurrence, sorted, or arbitrary, the RAM and scratch-disk budgets, maximum single-line length, and crash-resume expectations.
  • Sorted output (--order sorted): Use external merge sort, dropping adjacent duplicates both when writing sorted runs and during the k-way merge (a streaming pass that uses a min-heap—a tree keeping the smallest item on top—to merge k sorted files at once). For 200 GB input (75 GB unique) in 6 GB RAM: ~45 runs of 4.5 GB text, 1 merge pass, ~675 GB of sequential I/O (~22.5 minutes at 500 MB/s). On Unix, LC_ALL=C sort -u -S 6G provides this out of the box.
  • Arbitrary order (--order any): Use hash partitioning (routing each line to bucket file hash(line) % P with a deterministic hash like blake2b) into P = 32 buckets so each bucket's distinct set fits inside 6 GB RAM (accounting for ~2.3x hash-table memory overhead in Python or ~1.5x in C). Same ~675 GB sequential I/O, with O(N) hashing instead of O(N log N) sorting.
  • First-occurrence order (--order first): Prepend line_number during the partition scan. Because each bucket is written sequentially, its deduplicated survivors are already sorted by line_number, so a single P-way merge by line_number restores exact input order (~950 GB sequential I/O, zero sorting passes; doing the same via external sort takes two full external sorts).
  • Full byte comparison guarantees exactness: Hashes only route lines to buckets; inside each bucket, the set checks full byte equality. Storing only 64-bit fingerprints for 1.5 billion unique lines hits the birthday paradox (collisions among n items in 2^64 slots appear with probability ~1 - exp(-n^2 / 2^65) ≈ 6%), silently dropping unique lines.
  • Production edge cases: Delete consumed bucket files eagerly to cap peak disk use; stream multi-gigabyte single lines by chunk-hashing (digest, offset, length) and comparing byte streams on digest ties; checkpoint completed stages via temp files + fsync (flushing OS buffers to physical disk) + atomic rename.

Common mistakes

  • Using an in-memory set of lines or 64-bit hashes anyway: 75 GB of unique text overflows 6 GB RAM immediately, and even 1.5 billion raw 8-byte hashes require 12 GB before table overhead while losing ~6% of runs to hash collisions.
  • Answering sort -u without asking about output order or locale: Plain sort -u destroys first-occurrence order, and without LC_ALL=C, locale collation rules can treat distinct UTF-8 byte sequences as equal and drop one.
  • Routing partitions with Python's built-in hash(): Python randomizes hash() per process (PYTHONHASHSEED), so a restarted worker routes lines to completely different bucket files. Always use a fixed cryptographic or non-cryptographic digest like blake2b or xxHash.
  • Running a second sort on partitioned survivors: Because bucket files are written in input order and deduplicated sequentially, each bucket's kept (line_number, line) file is already sorted by line_number—only a linear k-way merge is needed.
  • Doing random disk reads per duplicate: Keeping (hash -> disk_offset) in memory and seeking into the input file on every match turns fast sequential streaming (500 MB/s) into millions of random I/O operations when duplicates are frequent.

Follow-up questions

  • How should the tool handle a skewed hash bucket whose distinct lines still exceed your RAM budget? First distinguish total file size from distinct line count: a 40 GB bucket file containing 800 million copies of the same line uses almost zero RAM in seen! Only when the in-memory set reaches the 6 GB ceiling while reading a bucket do we have true distinct-key skew (or an underestimated P). When that happens, spill and recursively re-partition just that one bucket file into sub-buckets using a different hash seed (blake2b(line, key=b"depth-2"))—never reuse the original hash bits, which would send every line back into the same sub-bucket. Because sub-buckets still preserve line_number order, the final k-way merge simply includes the sub-bucket outputs alongside the normal buckets; if recursion hits a depth cap (e.g., giant lines), fall back to external merge sort on that single bucket.
part_07 (9 GB distinct > 6 GB RAM) --rehash with seed="d2"--> part_07_0..3 (~2.25 GB distinct each)
  • Why does using a standalone Bloom filter risk silently dropping lines that appeared only once? A Bloom filter is a compact bit array of m bits with k hash functions: inserting a line sets k bit positions to 1, and querying checks whether all k positions are 1. It never produces false negatives ("if a bit is 0, we definitely have not seen this line"), but it suffers false positives when earlier distinct lines happen to set all k bit positions needed by a brand-new unique line, causing the filter to think the new line is a duplicate and silently discard it. For n = 1.5 billion unique lines with m / n = 10 bits per line (~1.88 GB RAM) and k = 7 hashes, the false-positive rate reaches (1 - exp(-7 / 10))^7 ≈ 0.82% when full, and averages 0.134% across the fill from 0 to 1.5 billion—silently deleting 0.00134 * 1.5e9 ≈ 2.0 million unique lines! A Bloom filter can only be used inside an exact tool as a Pass-1 pre-filter: lines returning False ("definitely unseen") are emitted immediately, while lines returning True ("maybe seen") are written to disk alongside the kept set for exact hash-partition verification, which helps only when duplicates are rare.

Follow-up questions

Similar questions

More Vanta interview questions

All 11 Vanta questions →