Building a Memory-Efficient Line Deduplication Tool
System DesignModel answerLast updated
Design a command-line tool that removes duplicate lines from files too large to fit in memory, using external sorting or partitioning.
You're building a command-line utility that reads a text file and outputs only unique lines. The challenge: the number of distinct lines is too large to hold in a hash table in RAM.
Your tool must:
- Remove all duplicate lines (exact string matches)
- Handle files where distinct lines exceed available memory
- Use disk storage as needed
- Produce correct output with no false positives or negatives
What to Address
- Algorithm design: How will you identify and remove duplicates when you can't keep all distinct lines in memory?
- Storage strategy: How will you use temporary disk space and manage I/O?
- Output ordering: How does preserving the original order of first occurrences change your approach versus allowing sorted output?
- Complexity analysis: What are the time and space trade-offs?
- Edge cases: How do you handle extremely long lines, I/O failures, or insufficient disk space?
Assume you have sufficient temporary disk space but limited RAM. Individual lines fit in memory. You may ask clarifying questions about ordering requirements and available resources.
Hints
Hint 1
External sorting can transform this into a streaming comparison problem
Hint 2
Partitioning by hash prefix lets you process subsets that fit in memory independently
Hint 3
Preserving original order requires either multiple passes or maintaining position metadata
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to avoid holding all distinct lines in memory simultaneously. Two main strategies exist: external sorting and hash-based partitioning.
Strategy 1: External Sorting (Sorted Output)
If sorted output is acceptable, external merge sort provides an elegant solution:
- Chunk and sort: Read the file in chunks that fit in memory, sort each chunk, write sorted chunks to disk
- Merge with deduplication: Perform k-way merge across sorted chunks, emitting each line only on its first occurrence during the merge
- Stream output: Since sorted runs are merged in order, consecutive duplicates are trivially detected
Complexity:
- Time: O(n log n) for sorting, where n is total lines
- Disk I/O: 2 passes (read once, write sorted chunks; read chunks, write final output)
- Memory: O(k × line_size) for k-way merge buffers, typically k = 100-1000
Code sketch:
def deduplicate_sorted(input_file, output_file, chunk_size):
# Phase 1: Sort chunks
chunk_files = []
with open(input_file) as f:
while chunk := read_chunk(f, chunk_size):
chunk.sort()
chunk_files.append(write_temp_chunk(chunk))
# Phase 2: K-way merge with dedup
with open(output_file, 'w') as out:
prev_line = None
for line in k_way_merge(chunk_files):
if line != prev_line:
out.write(line)
prev_line = line
Strategy 2: Hash Partitioning (Order Preservation)
To preserve original line order, partition by hash into files small enough to deduplicate in memory:
- Partition: Hash each line (e.g., first 64 bits of SHA-256) modulo P partitions, append to partition file P_i
- Deduplicate partitions: For each partition, load into hash set (fits in memory by design), scan original file, emit lines whose hash matches this partition and haven't been seen
- Stream output: Since we process in original file order, first occurrences are preserved
Choosing P: If distinct lines need D bytes and you have M bytes of RAM, set P ≈ D/M with safety margin. For 10GB distinct data and 1GB RAM, use P = 20-30 partitions.
Complexity:
- Time: O(P × n) — P passes over the input
- Disk: O(n) temporary storage for partitions
- Memory: O(M) constant
Alternative: Two-pass with positions:
- External sort with (line, position) pairs
- Deduplicate sorted list, keeping minimum position per unique line
- Sort deduplicated list by position, output in order
This reduces passes but requires storing positions (extra 8 bytes per line).
Common Mistakes
- Bloom filters alone: Probabilistic filters cause false positives; use only for optimization before exact checks
- Underestimating distinct count: Always assume worst case (all lines distinct) for partition sizing
- Ignoring line length variation: Use byte-based memory budgets, not line counts
- Single large hash table: Fails when distinct lines exceed RAM; must partition or sort
Edge Cases
- Very long lines (>1MB): Stream hash computation, buffer only hash + file offset
- Disk exhaustion: Check available space ≥ 2× input size before starting; fail fast
- Partial failures: Write output atomically (temp file + rename) or support resumption with checkpoint files
- Newline handling: Normalize line endings (CRLF vs LF) or treat as part of line content consistently
Production Considerations
Real implementations (GNU sort -u, database external merge) add:
- Adaptive partition counts based on runtime memory pressure
- Compressed temporary files (reduces I/O by 3-5×)
- Memory-mapped I/O for sequential scans
- Parallel sorting and merging
The external sort approach is simpler and faster when order doesn't matter; hash partitioning is necessary for order preservation and supports resumability more naturally.