Most Frequent Words in a File Tree
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an in-memory list files representing every text file collected recursively under a root directory, together with an integer k, return the k most frequent words across the entire file collection.
Each element of files is a dictionary containing two string keys:
"path": the file's path string (for example,"/logs/2026/worker.txt"), provided as metadata only and not counted as text."content": the body text of that file.
Word extraction and ranking follow these rules:
- Case folding: Convert all ASCII letters to lowercase before counting, so
"Cache","CACHE", and"cache"represent the same word. - Alphanumeric tokens: A word is a maximal contiguous sequence of lowercase ASCII letters and digits (
[a-z0-9]+). Spaces, tabs, newlines, and all punctuation or symbols act strictly as token boundaries ("miss,retry"splits into"miss"and"retry"). - File isolation: Tokenize each file separately so the end of one file never concatenates with the start of the next file.
- Ordering and ties: Order distinct words by total frequency descending, breaking equal-frequency ties in ascending alphabetical (
"a"to"z") order. - Result size: Return
[word, count]pairs for the topkwords. Return[]ifk <= 0or if no alphanumeric words appear infiles. If fewer thankdistinct words exist, return all distinct words in ranked order.
from typing import Dict, List
def top_k_word_frequencies(files: List[Dict[str, str]], k: int) -> List[List[object]]:
pass
Examples
Example 1
Input:
files = [
{"path": "/logs/api.txt", "content": "Cache hit! Cache miss, retry."},
{"path": "/logs/2026/worker.txt", "content": "Retry cache; miss."}
]
k = 3
Output:
[["cache", 3], ["miss", 2], ["retry", 2]]
Explanation: Lowercasing and splitting on non-alphanumeric characters yields ["cache", "hit", "cache", "miss", "retry"] from the first file and ["retry", "cache", "miss"] from the second. Total counts are "cache": 3, "miss": 2, "retry": 2, and "hit": 1. "cache" ranks first, followed by "miss" and "retry" in alphabetical order; "hit" falls outside k = 3.
Example 2
Input:
files = [
{"path": "/notes/ch1.md", "content": "pine oak pine"},
{"path": "/notes/ch2.md", "content": "oak elm"}
]
k = 2
Output:
[["oak", 2], ["pine", 2]]
Explanation: "pine" and "oak" each occur 2 times while "elm" occurs 1 time. Although "pine" appears earlier in the input, "oak" comes before "pine" alphabetically, producing [["oak", 2], ["pine", 2]].
Constraints
0 <= len(files) <= 10^40 <= sum(len(f["content"]) for f in files) <= 10^60 <= k <= 10^5- Target
O(C + U log k)time andO(U + k)auxiliary space (excluding per-file tokenization buffers), whereCis the total number of characters across all files andUis the number of distinct words.
Step-by-step walkthrough
Understand the input and word-counting rules
In a live service you would walk a directory tree on disk; here the judge provides every discovered file in
files, a list of{"path": ..., "content": ...}dictionaries. Our task is to return the topkwords across all file contents as[word, count]pairs.Every rule must match the problem specification:
- Case-insensitive:
"Cache"and"cache"both count toward"cache". - Alphanumeric word tokens: Punctuation and whitespace (
".",";",",","!", spaces, tabs, newlines) separate words rather than becoming part of them — so"miss,"and"miss."both become"miss", and"miss,retry"splits into"miss"and"retry". Each word is a maximal contiguous run of lowercase ASCII letters and digits ([a-z0-9]+). - Separate files stay separate: The last word of one file never glues onto the first word of the next file, and
"path"strings are metadata rather than counted text. - Tie-breaking order: Sort by frequency descending, and break ties by word ascending alphabetically (
[["oak", 2], ["pine", 2]]). - Boundary
kvalues: Ifk <= 0, return[]. Ifkexceeds the number of distinct words, return all distinct words in ranked order.
- Case-insensitive:
Why sorting every distinct word does extra work when k is small
Every exact solution must scan all
Ccharacters across the files at least once to count words, which takesO(C)time.Once we have the dictionary of
Udistinct words, the simplest ranking step sorts allUitems inO(U log U)time and slices[:k]. That works fine for small vocabularies, yet whenUis hundreds of thousands of words andkis only10, sorting the bottom99.99%of words is wasted work. Keeping a leaderboard of onlykentries with a heap (a tree-based priority queue stored inside a compact list) reduces selection toO(U log k)comparisons andO(k)extra memory.Key trick: encode the tie-breaker as (-count, word)
We want higher counts first, and on equal counts alphabetically smaller words first (
"miss"before"retry").Be careful: if you build a naive min-heap of
(count, word), equal counts put"miss"at the top of the min-heap because"miss" < "retry"— meaning"miss"would be evicted before"retry", backwards from what we want!Instead, we pair each word with its negated count:
(-count, word). Python compares tuples element by element from left to right:Files: /logs/api.txt -> "Cache hit! Cache miss, retry." /logs/2026/worker.txt -> "Retry cache; miss." 1. Tokenize & count (Counter): {"cache": 3, "miss": 2, "retry": 2, "hit": 1} 2. Convert to (-count, word) ranking keys: (-3, "cache") <- smallest negative number = highest count (3) (-2, "miss") <- tied at count 2: "miss" < "retry" alphabetically! (-2, "retry") (-1, "hit") 3. Take k = 3 smallest tuples via heapq.nsmallest: [(-3, "cache"), (-2, "miss"), (-2, "retry")] -> [["cache", 3], ["miss", 2], ["retry", 2]]Under
(-count, word), "best word" simply means "smallest tuple", soheapq.nsmallest(k, ...)handles both primary ordering and alphabetical tie-breaking automatically.Tokenize and count words file by file
We pre-compile
WORD_PATTERN = re.compile(r"[a-z0-9]+")once at module load. For each file,WORD_PATTERN.findall(file_entry["content"].lower())extracts every word token in one linear scan, andcounts.update(...)adds them into acollections.Counter.Note why we do not call
counts.most_common(k)afterward:Counter.most_commonbreaks equal-count ties by whichever word appeared first in the input, so"pine oak pine"+"oak elm"would return"pine"before"oak"and fail Example 2.from collections import Counter import heapq import re # WORD_PATTERN: matches maximal runs of lowercase ASCII letters and digits, # so punctuation, spaces, tabs, and newlines all act as word separators. WORD_PATTERN = re.compile(r"[a-z0-9]+") def count_words(files: List[Dict[str, str]]) -> Counter: """Count lowercase word frequencies across all file entries.""" # counts: Counter mapping word -> total occurrences across all files, # e.g. Counter({"cache": 3, "miss": 2, "retry": 2}). counts: Counter = Counter() for file_entry in files: # Tokenize each file separately so words never merge across file boundaries. words_in_file = WORD_PATTERN.findall(file_entry["content"].lower()) counts.update(words_in_file) return countsSelect the top k with heapq.nsmallest and connect directory walking
Rather than building a second full list of
Utuples in memory, we write a tiny generatoriter_ranking_keys(counts)that yields(-count, word)one item at a time intoheapq.nsmallest(k, ...). That keeps the selection buffer strictly bounded toO(k)memory.def iter_ranking_keys(counts: Counter) -> Iterator[Tuple[int, str]]: """Yield (-count, word) tuples so Python's natural tuple order ranks best first.""" # Negating count makes larger frequencies smaller numbers (-3 < -2), # while keeping word positive breaks equal counts alphabetically ("oak" < "pine"). for word, count in counts.items(): yield (-count, word) def top_k_word_frequencies(files: List[Dict[str, str]], k: int) -> List[List[object]]: # Guard against non-positive k immediately without scanning any files. if k <= 0: return [] # Phase 1: Build exact word frequencies across all files. counts = count_words(files) # Phase 2: Stream (-count, word) keys through a size-k heap so we use O(k) selection space # and O(U log k) comparisons instead of sorting all U distinct words. best_keys = heapq.nsmallest(k, iter_ranking_keys(counts)) # Phase 3: Unpack (-count, word) back into the required [word, count] output format. result: List[List[object]] = [] for negative_count, word in best_keys: result.append([word, -negative_count]) return resultIn a live interview where the input is a directory path on disk rather than a materialized
fileslist,os.walkstreams one file dictionary at a time directly intotop_k_word_frequencieswithout holding two files' contents in RAM simultaneously:import os def iter_files_under_path(root_path: str): for dirpath, dirnames, filenames in os.walk(root_path): for filename in filenames: full_path = os.path.join(dirpath, filename) with open(full_path, encoding="utf-8", errors="replace") as handle: yield {"path": full_path, "content": handle.read()}Trace Example 1 and Example 2 step by step
Let's verify our pipeline on both examples from the problem statement:
Example 1 (k = 3): File 1 ("/logs/api.txt"): "Cache hit! Cache miss, retry." -> tokens: ["cache", "hit", "cache", "miss", "retry"] File 2 ("/logs/2026/worker.txt"): "Retry cache; miss." -> tokens: ["retry", "cache", "miss"] Combined counts: "cache": 3, "miss": 2, "retry": 2, "hit": 1 3 smallest (-count, word) keys: 1st: (-3, "cache") 2nd: (-2, "miss") ("miss" < "retry") 3rd: (-2, "retry") Output: [["cache", 3], ["miss", 2], ["retry", 2]] Example 2 (k = 2): File 1 ("/notes/ch1.md"): "pine oak pine" -> ["pine", "oak", "pine"] File 2 ("/notes/ch2.md"): "oak elm" -> ["oak", "elm"] Combined counts: "pine": 2, "oak": 2, "elm": 1 Ranking keys: (-2, "oak") < (-2, "pine") < (-1, "elm") 2 smallest keys: [(-2, "oak"), (-2, "pine")] Output: [["oak", 2], ["pine", 2]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import Counter import heapq import re from typing import Iterator # WORD_PATTERN: matches maximal runs of lowercase ASCII letters and digits, # so punctuation, spaces, tabs, and newlines all act as word separators. WORD_PATTERN = re.compile(r"[a-z0-9]+") def count_words(files: List[Dict[str, str]]) -> Counter: """Count lowercase word frequencies across all file entries.""" # counts: Counter mapping word -> total occurrences across all files, # e.g. Counter({"cache": 3, "miss": 2, "retry": 2}). counts: Counter = Counter() for file_entry in files: # Tokenize each file separately so words never merge across file boundaries. words_in_file = WORD_PATTERN.findall(file_entry["content"].lower()) counts.update(words_in_file) return counts def iter_ranking_keys(counts: Counter) -> Iterator[Tuple[int, str]]: """Yield (-count, word) tuples so Python's natural tuple order ranks best first.""" # Negating count makes larger frequencies smaller numbers (-3 < -2), # while keeping word positive breaks equal counts alphabetically ("oak" < "pine"). for word, count in counts.items(): yield (-count, word) def top_k_word_frequencies(files: List[Dict[str, str]], k: int) -> List[List[object]]: # Guard against non-positive k immediately without scanning any files. if k <= 0: return [] # Phase 1: Build exact word frequencies across all files. counts = count_words(files) # Phase 2: Stream (-count, word) keys through a size-k heap so we use O(k) selection space # and O(U log k) comparisons instead of sorting all U distinct words. best_keys = heapq.nsmallest(k, iter_ranking_keys(counts)) # Phase 3: Unpack (-count, word) back into the required [word, count] output format. result: List[List[object]] = [] for negative_count, word in best_keys: result.append([word, -negative_count]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Think of finding the top k words across a folder hierarchy like tallying votes across thousands of precinct ballot boxes (files). First, a tokenizer (a text scanner that extracts clean lowercase word tokens while discarding punctuation and whitespace) reads one file at a time and updates a central tally sheet stored in a hash map (Counter, a dictionary mapping each unique word to its running count in O(1) average time). Once tallying finishes, instead of sorting the entire dictionary from top to bottom, we feed (-count, word) pairs into a size-k heap (a compact tree structure that retains only the k strongest candidates in O(log k) time per candidate).
Naive shortcuts fail in subtle ways on text inputs. Splitting only on spaces (content.split()) treats "Cache", "cache;", and "cache." as three unrelated strings, and concatenating every file's text into one giant buffer wastes memory and can accidentally fuse the last word of one file onto the first word of the next. Likewise, calling Counter.most_common(k) breaks equal-frequency ties by whichever word appeared first in the input rather than lexicographical order (standard alphabetical "a"-to-"z" dictionary order).
Walk through Example 2 with files = [{"path": "/notes/ch1.md", "content": "pine oak pine"}, {"path": "/notes/ch2.md", "content": "oak elm"}] and k = 2. Tokenizing each file in lowercase produces ["pine", "oak", "pine"] and ["oak", "elm"], giving counts = {"pine": 2, "oak": 2, "elm": 1}. Streaming (-count, word) yields (-2, "pine"), (-2, "oak"), and (-1, "elm"); because -2 == -2 and "oak" < "pine", heapq.nsmallest(2, ...) returns [(-2, "oak"), (-2, "pine")], which unpacks to [["oak", 2], ["pine", 2]].
Complexity
- Time:
O(C + U log k), whereCis the total number of characters across all files,Uis the number of distinct words, andkis the requested result size (with a word-length factor on tie comparisons). Lowercasing, regex scanning, and hashing every token inspects each character a constant number of times (O(C)), and streaming allUunique words throughheapq.nsmallest(k, ...)performsO(U log k)tuple comparisons (orO(1)whenk <= 0). - Space:
O(U + M + k), whereUis the vocabulary size stored incounts,Mis the size of the largest single file's lowercased text and token list (reclaimed before moving to the next file), andkis the size of the heap buffer (iter_ranking_keysyields tuples lazily instead of allocating a secondU-element list).
Edge cases
- Non-positive
k(k <= 0): Immediately returns[]without scanning any files. klarger than the number of distinct words (k > U): Returns allUdistinct words sorted by count descending, then alphabetically.- Empty file list, blank files, or punctuation-only files (
" ... !! \n"):countsstays empty and the function returns[]. - Multi-way ties straddling the
kcutoff: Withapple: 2, fig: 2, pear: 2andk = 2, alphabetical tie-breaking determines membership ([["apple", 2], ["fig", 2]]), not merely display order. - Punctuation inside tokens (
"miss,retry"or"api.v2"):[a-z0-9]+splits on any non-alphanumeric character, producing separate tokens cleanly. - Words at file boundaries: File 1 ending in
"log"and File 2 starting with"ger"stay two separate words ("log"and"ger"), never"logger". - Unicode and apostrophes:
[a-z0-9]+targets ASCII letters and digits ("don't"splits into"don"and"t"). If an interviewer wants full Unicode letters, state that assumption explicitly and switch to a Unicode-aware tokenizer.
Common mistakes
- Using
Counter.most_common(k)directly: It preserves first-seen order on ties instead of alphabetical order, returning[["pine", 2], ["oak", 2]]on Example 2. - Writing a manual size-
kmin-heap on(count, word): Among tied counts at the minimum of the heap, Python puts"apple"at the root ("apple" < "pear") and evicts"apple"first — the exact opposite of alphabetical tie-breaking! Using(-count, word)withheapq.nsmallest(or a custom comparison wrapper class for a manual min-heap) avoids this bug. - Materializing a full list of
Utuples beforeheapq.nsmallest: Building[(-c, w) for w, c in counts.items()]doubles peak vocabulary memory and causesheapq.nsmallestto fall back to sorting whenk >= len(list)instead of streaming. - Splitting on
" "instead of tokenizing:line.split(" ")leaves trailing punctuation attached ("cache;" != "cache") and creates empty strings""whenever two spaces appear in a row.
Alternative approaches
- Full sort (
sorted(..., key=lambda item: (-item[1], item[0]))[:k]): Runs inO(C + U log U)time andO(U)space; slightly slower asymptotically whenUis huge andkis tiny, yet very concise whenUis moderate. - Bucket sort by frequency: Because any word's count lies between
1and total word tokensN, you can group words by frequency inO(N + U)time and walk buckets downward from highest count, sorting alphabetically only inside buckets you actually take. - Quickselect (
O(U)average selection +O(k log k)sort): Partitions theUtuples around random pivots to isolate theksmallest in linear average time, then sorts just thosekwinners.
Follow-up questions
- How can you find exact top-k word counts on one machine when neither the text collection nor the unique vocabulary fits in RAM? Use hash partitioning (splitting tokens across
Ptemporary disk buckets viahash(word) % Pso every occurrence of a given word lands in the exact same bucket file). Stream through all files once, flushing small local(word, partial_count)maps to their assigned bucket files on disk; then load one bucket file at a time into an in-memoryCounterto obtain exact global totals for that bucket's words while maintaining a single size-kheap across allPbuckets. An alternative is external merge sort, which writes sorted word runs to disk and merges them so identical words sit adjacent and can be tallied inO(1)RAM, though sorting costsO(N log N)disk work compared toO(N)sequential I/O for hash partitioning. - How would you distribute exact word counting and top-k aggregation across a multi-node cluster? Split the file list across mapper workers that tokenize assigned files in parallel and aggregate local counts in a bounded hash table (a combiner step that collapses repeated words like
"the"before touching the network). Mappers route each(word, subtotal)pair to reducerhash(word) % Rso one reducer receives every subtotal for a given word, sums its exact frequency, and keeps only its local topkin a size-kheap. Finally, a single coordinator merges theR * kfinalists from all reducers inO(R * k log k)time to emit the global topk. - If approximate results are acceptable on a massive stream, which probabilistic data structures estimate heavy hitters and what trade-offs do they introduce? A Count-Min Sketch maintains a fixed
d x wgrid of integer counters (w = ceil(e / epsilon),d = ceil(ln(1 / delta))) indexed bydindependent hash functions: each token increments one cell per row, and querying the minimum across thosedcells never undercounts and overcounts by at mostepsilon * Nwith probability1 - delta(using ~54 KB of RAM forepsilon = 0.001, delta = 0.01), paired with a size-kcandidate heap. Alternatively, the Space-Saving summary tracksmexplicit(word, count)counters and replaces the minimum-count entry when a new word arrives, guaranteeing deterministic count error<= N / mand retaining every word whose true count exceedsN / m. Both run in a single streaming pass with tiny constant memory and sub-microsecond latency, at the cost of approximate counts that can reorder or miss words whose frequencies sit near theepsilon * N(orN / m) error margin.
Follow-up questions
- How can you find exact top-k word counts on one machine when neither the text collection nor the unique vocabulary fits in RAM?
- How would you distribute exact word counting and top-k aggregation across a multi-node cluster?
- If approximate results are acceptable on a massive stream, which probabilistic data structures estimate heavy hitters and what trade-offs do they introduce?
Similar questions
- Sliding-Window Payload Average on Out-of-Order Events
- Toggle Target Bit of an Integer
- Thread-Safe Leaky Bucket Rate Limiter
- Simulate a Leaky-Bucket Request Meter
- Top-K Word Frequencies Across Document Collections
- Live SSH Log Triage and Centralized Logging Architecture
More Box interview questions
- Live SSH Log Triage and Centralized Logging Architecture Medium
- Whiteboarding a Production System You Owned Hard
- Toggle Target Bit of an Integer Medium Pro
- Diagnosing and Preventing Multithreaded Lock Deadlocks Medium Pro
- Simulate a Leaky-Bucket Request Meter Hard Pro
- Sliding-Window Payload Average on Out-of-Order Events Medium Pro
- Thread-Safe Leaky Bucket Rate Limiter Easy Pro
- Top-K Word Frequencies Across Document Collections Medium Pro