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
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\nsolely 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 writeAn ordinary in-memory
setstores every unique line at once. Even with zero data-structure overhead,75 GBof distinct text cannot fit in6 GBof 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")- Byte-exact equality: Compare raw UTF-8/byte sequences (
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.
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:
- Run generation: Read lines until our
6 GBworking 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), a6 GBbudget holds roughly6 GB * (50 / 66) = 4.5 GBof raw text per run, producing200 GB / 4.5 GB ≈ 45run files. - k-way merge: Open all
45sorted runs at once with a100 MBsequential read buffer per run (45 * 100 MB = 4.5 GB, comfortably inside6 GBRAM). Use a min-heap (a priority queue that pops the smallest current line across all45runs inO(log 45)time) and write each line only if it differs fromprevious_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, write200 GBof runs, read200 GBof runs back, and write75 GBof unique output =675 GBof sequential I/O, or675,000 MB / 500 MB/s ≈ 22.5 minutes. On Unix,LC_ALL=C sort -u -S 6G -T /tmp/runs input.txt > output.txtimplements this directly (LC_ALL=Cforces 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- Run generation: Read lines until our
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 intoPbucket files usinghash(item) % P) avoids sorting altogether:- Partition pass (
O(N)): Stream the input once. For each line, compute a deterministic hashhand append the line to bucket fileh % P. Because equal byte strings always produce the exact same hash, every copy of lineXlands in the same bucket file. - Per-bucket deduplication (
O(N)): Each bucket holds roughly1 / Pof the distinct lines (duplicates do not grow the in-memory set!). Load one bucket file at a time into a fresh in-memoryset, emit each first-seen line to the final output, clear theset, and delete that bucket file.
How to size
P: Raw distinct text is75 GB, but hash tables have per-entry overhead. In 64-bit CPython, a 49-bytebytesobject plus itssetslot costs ~115 bytes(~2.3xraw text, or~173 GBacross1.5Bdistinct lines). Dividing173 GBby our6 GBbudget gives29buckets; rounding up toP = 32puts~2.34 GBof raw distinct text (~5.4 GBin a CPython set, or ~3.5 GBin a compact C/Rust hash table) per bucket. Always use a deterministic hash likehashlib.blake2b—Python's built-inhash()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)- Partition pass (
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 increasingline_numberorder. 2. When Pass 2 deduplicates each bucket sequentially, the first copy of any line it encounters is guaranteed to have the smallestline_number, and the surviving(line_number, line)records written tokept_iremain already sorted byline_number! 3. A singleP-way streaming merge byline_numberacrosskept_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, cBy contrast, preserving first-occurrence order with external merge sort requires two full external sorts: first sort
(line, line_number)to keep the smallestline_numberper distinct line, then run a second external sort on those1.5 billionsurvivors ordered byline_number. Carrying 8-byte binary line numbers across4 billionlines adds32 GBof temporary disk data (~43 GBif formatted as ASCII digits plus\t), raising total sequential I/O for hash partitioning + k-way merge from675 GBto roughly950 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")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 seencompares the entire byte sequence on any hash match.Why not avoid disk partitioning by keeping an in-memory set of 64-bit hashes (
8 bytesper unique line)? Two reasons: 1. Even 64-bit hashes exceed RAM here:1.5 billion * 8 bytes = 12 GBof raw hashes before hash-table slot overhead—already twice our6 GBlimit. 2. Silent data loss from the birthday paradox: The birthday paradox is the probability phenomenon where collisions amongnrandom draws fromMpossibilities become likely aroundsqrt(M)items, long beforeM. WithM = 2^64 ≈ 1.84 * 10^19possible 64-bit hashes andn = 1.5 * 10^9distinct lines, the number of distinct pairs isn * (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-256truncated to 128 bits, collision probability~3 * 10^-21at1.5Blines) still is not mathematically exact—and1.5B * 16 bytes = 24 GBstill overflows6 GBRAM anyway. Partitioning full lines to disk gives 100% mathematical exactness within bounded memory.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 GBof temp disk (deleting eachpart_iright after writingkept_i). If temp disk is nearly zero and any output order is allowed, trade disk writes for sequential reads: runP = 32passes over the input file, keeping an in-memory set only for lines wherehash(line) % 32 == pass_id(0bytes of temporary disk, at the cost of reading200 GB * 32 = 6.4 TB, ~3.5 hoursat500 MB/s). - Single line larger than 6 GB RAM: Stream input in fixed
1 MBchunks instead ofreadline(). If a line crosses a size threshold (say64 MB), feed its chunks incrementally intoblake2bwithout buffering the whole line in RAM, and store(digest, file_offset, byte_length)as a proxy record. Only if two giant lines share bothbyte_lengthanddigestdo we open two file cursors at theirfile_offsets and compare1 MBchunks side by side. - Crash recovery / restarts: Write each completed stage (
part_0..31, eachkept_i, final output) to a.tmpfile, callfsync(an OS call that forces buffered file data onto physical storage before returning), atomicallyos.replace()it to its final name, and log the stage in a tinymanifest.json. Becauseblake2brouting 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)- Tight temporary disk space: Partitioning needs ~
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 mergeksorted files at once). For200 GBinput (75 GBunique) in6 GBRAM: ~45runs of4.5 GBtext, 1 merge pass, ~675 GBof sequential I/O (~22.5 minutesat500 MB/s). On Unix,LC_ALL=C sort -u -S 6Gprovides this out of the box. - Arbitrary order (
--order any): Use hash partitioning (routing each line to bucket filehash(line) % Pwith a deterministic hash likeblake2b) intoP = 32buckets so each bucket's distinct set fits inside6 GBRAM (accounting for ~2.3xhash-table memory overhead in Python or ~1.5xin C). Same ~675 GBsequential I/O, withO(N)hashing instead ofO(N log N)sorting. - First-occurrence order (
--order first): Prependline_numberduring the partition scan. Because each bucket is written sequentially, its deduplicated survivors are already sorted byline_number, so a singleP-way merge byline_numberrestores exact input order (~950 GBsequential 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 billionunique lines hits the birthday paradox (collisions amongnitems in2^64slots 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
setof lines or 64-bit hashes anyway:75 GBof unique text overflows6 GBRAM immediately, and even1.5 billionraw 8-byte hashes require12 GBbefore table overhead while losing ~6%of runs to hash collisions. - Answering
sort -uwithout asking about output order or locale: Plainsort -udestroys first-occurrence order, and withoutLC_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 randomizeshash()per process (PYTHONHASHSEED), so a restarted worker routes lines to completely different bucket files. Always use a fixed cryptographic or non-cryptographic digest likeblake2borxxHash. - 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 byline_number—only a lineark-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 GBbucket file containing 800 million copies of the same line uses almost zero RAM inseen! Only when the in-memorysetreaches the6 GBceiling while reading a bucket do we have true distinct-key skew (or an underestimatedP). 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 preserveline_numberorder, the finalk-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
mbits withkhash functions: inserting a line setskbit positions to1, and querying checks whether allkpositions are1. It never produces false negatives ("if a bit is0, we definitely have not seen this line"), but it suffers false positives when earlier distinct lines happen to set allkbit positions needed by a brand-new unique line, causing the filter to think the new line is a duplicate and silently discard it. Forn = 1.5 billionunique lines withm / n = 10bits per line (~1.88 GBRAM) andk = 7hashes, the false-positive rate reaches(1 - exp(-7 / 10))^7 ≈ 0.82%when full, and averages0.134%across the fill from0to1.5 billion—silently deleting0.00134 * 1.5e9 ≈ 2.0 millionunique lines! A Bloom filter can only be used inside an exact tool as a Pass-1 pre-filter: lines returningFalse("definitely unseen") are emitted immediately, while lines returningTrue("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
- How should the tool handle a skewed hash bucket whose distinct lines still exceed your RAM budget?
- Why does using a standalone Bloom filter risk silently dropping lines that appeared only once?
Similar questions
- Mastering and Applying a Recent Technical Skill
- Consumer Engagement Metrics Pipeline for DAU and MAU
- Real-Time Test Status Logger and Interval Queries
- Streaming Test Status Logger and Failure Analytics
- Driving Unowned Engineering Improvements With Senior Leadership
- Streaming Adjacent Line Deduplicator
More Vanta interview questions
- Mastering and Applying a Recent Technical Skill Medium
- Consumer Engagement Metrics Pipeline for DAU and MAU Medium
- Driving Unowned Engineering Improvements With Senior Leadership Medium Pro
- Consecutive Line Run Deduplicator Medium Pro
- Top-URL Traffic and Paid Conversion Analytics System Medium Pro
- Observability, Debugging, and Safe Rollout for an Enterprise Compliance Assistant Medium Pro
- Real-Time Test Status Logger and Interval Queries Medium Pro
- Streaming Test Status Logger and Failure Analytics Medium Pro
- Streaming Adjacent Line Deduplicator Easy Pro
- Deterministic Course Ordering via Recursive DFS Medium Pro