Streaming Word Frequencies from an Oversized Text File
Heaps, Sorting & SearchModel answerLast 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
- 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.
- 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.
- Top-k selection. Return the
kmost frequent words. Ties must be broken deterministically: higher count first, then alphabetical order. - Complexity. Give time and space bounds in terms of file length
N, number of distinct wordsU, andk. - 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,
klarger than the number of distinct words, ork <= 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract
Agree on these rules first, since "word" is ambiguous and the answer depends on them.
- Input: path to a UTF-8 file, possibly larger than RAM.
- Output: a
word -> countmapping and atop_k(counts, k)helper. - Ordering: count descending, then word ascending, so output is deterministic.
- Normalization:
- Apply Unicode NFKC so ligatures like
fiand full-width letters collapse to plain forms. - Use
casefold()rather thanlower(); it handles cases such as Germanß. - Map curly and modifier apostrophes to
'.
- Apply Unicode NFKC so ligatures like
- Token: a maximal run of letters and digits, optionally joined by single internal apostrophes. So
don'tando'clockare single words,'hello'becomeshello, andstate-of-the-artbecomes four words. Numbers such as2024count as words; say so explicitly.
Approach
- Stream. Open the file in text mode and read fixed-size character chunks. The decoder deals with multi-byte UTF-8 sequences that cross chunk boundaries.
- Protect boundary words. Concatenate the carry from the previous chunk with the new chunk, find the last whitespace, process everything up to it, and carry the remainder. If there is no whitespace, keep accumulating. This is also safe for normalization, because combining marks attach to a preceding base character, never to whitespace.
- Count with a hash map (
Counter). Memory is O(U), not O(N). - Top-k with a bounded heap keyed by
(-count, word).
Code
import heapq
import re
import unicodedata
from collections import Counter
from typing import Dict, List, Tuple
_TOKEN_RE = re.compile(r"[^\W_]+(?:'[^\W_]+)*")
_APOS = str.maketrans({"\u2019": "'", "\u02bc": "'", "\uff07": "'"})
def _normalize(text: str) -> str:
return unicodedata.normalize("NFKC", text).translate(_APOS).casefold()
def _count_into(counts: Counter, text: str) -> None:
counts.update(_TOKEN_RE.findall(_normalize(text)))
def count_words(path: str, chunk_chars: int = 1 << 20) -> Dict[str, int]:
counts: Counter = Counter()
carry = ""
with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
while True:
chunk = f.read(chunk_chars)
if not chunk:
break
buf = carry + chunk
cut = len(buf)
while cut > 0 and not buf[cut - 1].isspace():
cut -= 1
if cut == 0: # no whitespace yet, keep accumulating
carry = buf
continue
_count_into(counts, buf[:cut])
carry = buf[cut:]
if carry:
_count_into(counts, carry)
return dict(counts)
def top_k(counts: Dict[str, int], k: int) -> List[Tuple[str, int]]:
if k <= 0:
return []
return heapq.nsmallest(k, counts.items(), key=lambda kv: (-kv[1], kv[0]))
Why it is correct
- Every character is tokenized exactly once, and tokens never contain whitespace, so cutting at whitespace cannot split a token.
- A chunk with no whitespace just extends the carry, so a long token is still counted whole. The final carry is flushed at EOF.
- Normalization runs before tokenization, so equivalent spellings share one key.
- The key
(-count, word)encodes exactly the required tie-break.
Complexity
| Phase | Time | Space |
|---|---|---|
| Read, normalize, tokenize | O(N) | O(chunk) |
| Counting | O(N) expected | O(U · average word length) |
| Top-k | O(U log k) | O(k) |
Peak memory is O(chunk + U) and independent of N. Vocabularies grow sublinearly with text size (Heaps' law), so U is typically much smaller than N.
Edge cases
- Empty file or punctuation only: empty counts, empty top-k.
k >= U: returns every word.k <= 0: returns an empty list.- No newlines or no whitespace at all: works, since chunking never relies on lines.
- BOM:
utf-8-sigstrips it. - Invalid bytes:
errors="replace"keeps a multi-GB job alive; mention failing loudly as the strict alternative.
Trade-offs when the vocabulary is large
Hash map (default). Expected O(1) updates and simple. The downside is per-entry overhead: in CPython roughly 100 bytes or more per distinct word, so ten million distinct tokens can exceed 1 GB. Mitigations include storing keys as bytes, using a native implementation with a string arena, or mapping words to integer ids.
Trie. Shares prefixes, supports prefix queries, and can emit words in sorted order. A naive pointer-per-node trie usually uses more memory than a hash map and has poor cache behavior. It pays off only in compressed forms (radix tree, DAWG, double-array trie), and when you need prefix operations rather than raw counting speed.
External approaches when U does not fit.
-
Hash partitioning (preferred).
- Stream tokens and append each to one of
Pspill files chosen by a stable hash such ascrc32(word) % P. Avoid Python's per-process randomizedhash. - Each file holds a disjoint set of words, so count each in memory and keep a local top-k heap.
- Merge the
Pheaps into the global top-k.
This costs O(N) time with sequential I/O, and memory is about U/P per partition. Pick
Pso each partition fits comfortably. - Stream tokens and append each to one of
-
External merge sort. Write sorted runs of tokens, k-way merge them, and count equal adjacent keys. It costs O(N log N) and more I/O, but it also yields sorted output and handles any size.
-
Approximate options. If only heavy hitters are needed, Count-Min Sketch with a small heap, or Misra-Gries / Space-Saving, gives bounded memory at the cost of approximate counts. State clearly that this changes the exact-answer guarantee.
Common mistakes
- Splitting on a fixed byte count and cutting a word or a multi-byte character in half.
- Using
lower()instead ofcasefold(), or skipping Unicode normalization. - Sorting all U entries when only
kare needed. - Using a non-deterministic tie-break, so results differ between runs.
- Using an unstable hash for partitioning, which breaks reproducibility.
- Not stating the tokenization rules, so the interviewer cannot tell whether "don't" and "state-of-the-art" are handled intentionally.
Possible follow-ups
- Parallelize: split the file by byte ranges aligned to whitespace, count per worker, merge counters.
- Stream results as the file grows: maintain the counter incrementally and a heap or sketch for live top-k.
- Multi-language text: languages without spaces (Chinese, Japanese) need a segmenter instead of whitespace chunking.