KatInterview

Building a Memory-Efficient Line Deduplication Tool

System DesignModel answer
MediumModel answerSystem Designexternal-memorydeduplicationsorting

Last 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

  1. Algorithm design: How will you identify and remove duplicates when you can't keep all distinct lines in memory?
  2. Storage strategy: How will you use temporary disk space and manage I/O?
  3. Output ordering: How does preserving the original order of first occurrences change your approach versus allowing sorted output?
  4. Complexity analysis: What are the time and space trade-offs?
  5. 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