Top Words in a Huge Text File Under Tight Memory
Heaps, Sorting & SearchModel answerLast 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:
- 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.
- 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).
- How to get the top K efficiently. Avoid sorting the full vocabulary if K is small. Define a deterministic tie-break.
- Complexity. Give time, memory and disk usage in terms of the input size, number of tokens, number of distinct words, and K.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
The interesting part is not Counter. A strong answer defines "word" precisely, streams the input, recognizes that the vocabulary itself can exceed RAM, and extracts top-K without a full sort.
1. Tokenization contract
State these rules up front and apply them deterministically:
- Decoding: UTF-8, stripping a BOM (
utf-8-sig), witherrors="replace"so one corrupt byte does not kill a multi-gigabyte job. The replacement character is treated as a separator. - Normalization: NFKC, so
eplus a combining accent equalsé, ligatures likefibecomefi, and full-width letters become ASCII. - Case:
str.casefold()rather thanlower(), soStraßeandSTRASSEmatch. - Word: a maximal run of Unicode letters and digits, optionally with internal apostrophes (
don't). Map the typographic’to'first. - Separators: everything else, including hyphens, underscores, punctuation, emoji and whitespace.
state-of-the-artis four words.
Other choices (keeping hyphenated compounds, dropping pure numbers) are fine if stated.
2. Streaming without breaking words
Read fixed-size character chunks. In each chunk, find the last whitespace, tokenize everything up to it, and carry the tail into the next chunk. Because whitespace is always a separator, tokenizing pieces gives exactly the same tokens as tokenizing the whole file. Normalization never crosses whitespace, so applying it per piece is safe too.
Cap the carry buffer (say 16 chunks). A pathological token with no whitespace, such as a base64 blob, is force-split so memory stays bounded.
3. When the vocabulary does not fit
Two tiers:
Tier 1, in memory. Keep a Counter while it has fewer than M distinct entries.
Tier 2, spill and reduce (a hash-partitioned combiner/reducer):
- When the counter exceeds
Mentries, write each(word, partial_count)to one ofPpartition files chosen by a stable hash (crc32(word) % P), then clear the counter. Writing pre-aggregated partials costs far less I/O than one line per token. - After the scan, flush any remaining counter content the same way.
- For each partition, load it into a fresh
Counter, summing partials. All occurrences of a word are in one partition, and each partition has aboutV/Pdistinct words, so it fits ifPis chosen well. If a partition is still too big, re-partition it with a different hash seed.
Use a stable hash, not Python's hash(), which is randomized per process.
Alternative: external sort. Write sorted runs of tokens, k-way merge them, and count adjacent equal words. It also works in bounded memory but costs O(T log T) with more I/O, so hash partitioning is usually preferable unless sorted output is required.
4. Top-K
Stream the final (word, count) pairs through a bounded heap of size K, keyed on (-count, word). Equivalent to heapq.nsmallest(k, pairs, key=...). That costs O(V log K) rather than O(V log V). Merging the running top-K with each partition's results is exact: each word has its final count in exactly one partition, and a word evicted from the running top-K can never re-enter, since K better candidates already exist.
The tie-break (count descending, then word ascending) makes output deterministic and testable.
5. Code sketch
import heapq, os, re, tempfile, unicodedata, zlib
from collections import Counter
TOKEN_RE = re.compile(r"[^\W_]+(?:'[^\W_]+)*")
def tokenize(text):
text = unicodedata.normalize("NFKC", text).casefold().replace("\u2019", "'")
return TOKEN_RE.findall(text)
def token_batches(path, chunk_chars):
carry, max_carry = "", 16 * chunk_chars
with open(path, encoding="utf-8-sig", errors="replace", newline="") as f:
while chunk := f.read(chunk_chars):
buf = carry + chunk
i = len(buf) - 1
while i >= 0 and not buf[i].isspace():
i -= 1
if i < 0:
if len(buf) < max_carry:
carry = buf
continue
i = len(buf) - 1 # force split
yield tokenize(buf[: i + 1])
carry = buf[i + 1:]
if carry:
yield tokenize(carry)
def word_count(path, top_k=10, max_entries=500_000,
num_partitions=64, chunk_chars=1 << 22):
if top_k <= 0:
return []
with tempfile.TemporaryDirectory() as tmp:
files, counts = None, Counter()
def spill():
nonlocal files
if files is None:
files = [open(os.path.join(tmp, f"p{i}.tsv"), "w", encoding="utf-8")
for i in range(num_partitions)]
for w, c in counts.items():
files[zlib.crc32(w.encode()) % num_partitions].write(f"{w}\t{c}\n")
counts.clear()
for batch in token_batches(path, chunk_chars):
counts.update(batch)
if len(counts) > max_entries:
spill()
key = lambda kv: (-kv[1], kv[0])
if files is None: # everything fit in memory
return heapq.nsmallest(top_k, counts.items(), key=key)
spill()
for f in files:
f.close()
top = []
for i in range(num_partitions):
part = Counter()
with open(os.path.join(tmp, f"p{i}.tsv"), encoding="utf-8") as f:
for line in f:
w, c = line.rstrip("\n").rsplit("\t", 1)
part[w] += int(c)
top = heapq.nsmallest(top_k, list(top) + list(part.items()), key=key)
return top
6. Complexity
Let N be characters, T tokens, V distinct words, M the in-memory limit, K the result size.
- Time: O(N) for normalization and tokenizing, O(T) counter updates, O(V log K) for top-K. Overall O(N + V log K).
- Memory: O(M + K + chunk size) in the scan; O(V/P) per partition in the reduce. Independent of file size.
- Disk: at most O(T), usually far less thanks to combining.
7. Edge cases and common mistakes
- Empty file or
K = 0returns[]. - Files with no newlines work because chunking ignores line structure. Reading line by line would not.
- Invalid bytes become U+FFFD and act as separators.
- Digit-only tokens count as words under this rule.
- Mixed
’and'unify.
Common mistakes:
- Reading the whole file or using
readlines(). - Cutting chunks mid-word and double-counting fragments.
- Using
lower()and skipping Unicode normalization. - Sorting the whole vocabulary for a small K.
- Using Python's randomized
hash()for partitioning. - Forgetting that the dictionary of distinct words can itself overflow memory.
- Leaving ties unspecified, which makes outputs non-deterministic.
If the interviewer pushes further, mention parallelism (map over file byte ranges, then merge partition counts) and approximate alternatives such as Count-Min Sketch plus a heap, with the caveat that they give approximate rather than exact counts.