KatInterview

Top Words in a Huge Text File Under Tight Memory

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchword-countstreamingexternal-memory

Last updated

Count word frequencies in a text file far larger than RAM, with explicit tokenization rules and an efficient exact top-K, and analyze time, memory and disk costs.

You are given the path to a plain-text file that may be many times larger than the memory on your machine. Design and implement a function that reports how often each word occurs and returns the K most frequent words.

Your answer should cover:

  1. What counts as a word. Spell out your rules for character encoding, Unicode normalization, case handling, punctuation, apostrophes, hyphens, digits and invalid bytes. Any sensible rule set is fine, but it must be explicit and applied consistently.
  2. How to handle input bigger than RAM. Explain how you read the file without loading it whole, and what you do if even the table of distinct words does not fit in memory (for example, by chunking, spilling partial counts to disk, or using an external sort).
  3. How to get the top K efficiently. Avoid sorting the full vocabulary if K is small. Define a deterministic tie-break.
  4. Complexity. Give time, memory and disk usage in terms of the input size, number of tokens, number of distinct words, and K.
  5. Edge cases. Empty file, K = 0, a file with no newlines, very long tokens, malformed UTF-8.

Write the function (Python is fine) with a signature along the lines of:

def word_count(path: str, top_k: int = 10) -> list[tuple[str, int]]:
    ...

The result should be ordered by count descending, then by word ascending.

Hints

Hint 1

Decide the tokenization contract first. Apply Unicode normalization and case folding (not just lowercasing) before extracting tokens, and say what happens to apostrophes, hyphens and underscores.

Hint 2

Reading in fixed-size chunks is only safe if you never cut a word in half: split each chunk at its last whitespace and carry the remainder into the next read. Remember that a streaming reader alone does not solve the problem if the number of distinct words is huge.

Hint 3

When the in-memory counter grows too large, flush its partial (word, count) pairs into hash-based partition files so every occurrence of a word lands in the same file. Then reduce each partition independently and keep a size-K heap across partitions.