KatInterview

Streaming Word Frequencies from an Oversized Text File

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchword-countstreaminghash-map

Last updated

Build a memory-safe word counter for a huge text file, define tokenization rules, return the top-k words deterministically, and discuss what to do when the vocabulary strains memory.

You are given the path to a UTF-8 text file that may be far larger than available RAM. Design and implement a routine that produces a frequency table of the words in the file, plus a helper that returns the k most common words.

What to cover

  1. Tokenization rules. State precisely what counts as a word and how you normalize text before counting. Address:
    • letter case,
    • Unicode equivalence (compatibility forms, full-width characters, ligatures),
    • punctuation and hyphenated terms,
    • contractions and different apostrophe characters,
    • numbers.
  2. Memory control. Explain how you read the file so memory does not grow with file size, including how you avoid splitting a word that straddles two reads.
  3. Top-k selection. Return the k most frequent words. Ties must be broken deterministically: higher count first, then alphabetical order.
  4. Complexity. Give time and space bounds in terms of file length N, number of distinct words U, and k.
  5. Trade-offs. Compare a hash map, a trie, and an external (disk-based) approach for the case where the distinct vocabulary itself barely fits, or does not fit, in memory.

Edge cases to handle

  • an empty file or one with no word characters,
  • k larger than the number of distinct words, or k <= 0,
  • a file with no newlines (or no whitespace at all),
  • a byte-order mark or invalid UTF-8 bytes.

Example. For the text Don't stop. DON’T stop—don't! with the rules you define (apostrophes inside a word are kept, em dash separates words), the counts are don't: 3 and stop: 2, and the top-1 result is ("don't", 3).

Hints

Hint 1

Write down the definition of a word before any code: decide how case folding, Unicode normalization, hyphens and inner apostrophes behave. A regex for runs of letters and digits that allows an apostrophe between two word characters covers most of it.

Hint 2

Read fixed-size chunks, but only process up to the last whitespace in the buffer and carry the tail into the next read. If a chunk has no whitespace, keep growing the carry. Flush the carry at EOF.

Hint 3

For top-k, do not sort all U entries. Keep a bounded heap of size k keyed by (-count, word), which costs O(U log k). For the oversized-vocabulary case, think about hash-partitioning tokens into spill files so each partition can be counted independently.