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:

  1. Case folding: Convert all ASCII letters to lowercase before counting, so "Cache", "CACHE", and "cache" represent the same word.
  2. 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").
  3. File isolation: Tokenize each file separately so the end of one file never concatenates with the start of the next file.
  4. Ordering and ties: Order distinct words by total frequency descending, breaking equal-frequency ties in ascending alphabetical ("a" to "z") order.
  5. Result size: Return [word, count] pairs for the top k words. Return [] if k <= 0 or if no alphanumeric words appear in files. If fewer than k distinct 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^4
  • 0 <= sum(len(f["content"]) for f in files) <= 10^6
  • 0 <= k <= 10^5
  • Target O(C + U log k) time and O(U + k) auxiliary space (excluding per-file tokenization buffers), where C is the total number of characters across all files and U is the number of distinct words.

Step-by-step walkthrough

  1. 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 top k words 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 k values: If k <= 0, return []. If k exceeds the number of distinct words, return all distinct words in ranked order.
  2. Why sorting every distinct word does extra work when k is small

    Every exact solution must scan all C characters across the files at least once to count words, which takes O(C) time.

    Once we have the dictionary of U distinct words, the simplest ranking step sorts all U items in O(U log U) time and slices [:k]. That works fine for small vocabularies, yet when U is hundreds of thousands of words and k is only 10, sorting the bottom 99.99% of words is wasted work. Keeping a leaderboard of only k entries with a heap (a tree-based priority queue stored inside a compact list) reduces selection to O(U log k) comparisons and O(k) extra memory.

  3. 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", so heapq.nsmallest(k, ...) handles both primary ordering and alphabetical tie-breaking automatically.

  4. 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, and counts.update(...) adds them into a collections.Counter.

    Note why we do not call counts.most_common(k) afterward: Counter.most_common breaks 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 counts
    
  5. Select the top k with heapq.nsmallest and connect directory walking

    Rather than building a second full list of U tuples in memory, we write a tiny generator iter_ranking_keys(counts) that yields (-count, word) one item at a time into heapq.nsmallest(k, ...). That keeps the selection buffer strictly bounded to O(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 result
    

    In a live interview where the input is a directory path on disk rather than a materialized files list, os.walk streams one file dictionary at a time directly into top_k_word_frequencies without 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()}
    
  6. 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]]
    
  7. 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), where C is the total number of characters across all files, U is the number of distinct words, and k is 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 all U unique words through heapq.nsmallest(k, ...) performs O(U log k) tuple comparisons (or O(1) when k <= 0).
  • Space: O(U + M + k), where U is the vocabulary size stored in counts, M is the size of the largest single file's lowercased text and token list (reclaimed before moving to the next file), and k is the size of the heap buffer (iter_ranking_keys yields tuples lazily instead of allocating a second U-element list).

Edge cases

  • Non-positive k (k <= 0): Immediately returns [] without scanning any files.
  • k larger than the number of distinct words (k > U): Returns all U distinct words sorted by count descending, then alphabetically.
  • Empty file list, blank files, or punctuation-only files (" ... !! \n"): counts stays empty and the function returns [].
  • Multi-way ties straddling the k cutoff: With apple: 2, fig: 2, pear: 2 and k = 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-k min-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) with heapq.nsmallest (or a custom comparison wrapper class for a manual min-heap) avoids this bug.
  • Materializing a full list of U tuples before heapq.nsmallest: Building [(-c, w) for w, c in counts.items()] doubles peak vocabulary memory and causes heapq.nsmallest to fall back to sorting when k >= 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 in O(C + U log U) time and O(U) space; slightly slower asymptotically when U is huge and k is tiny, yet very concise when U is moderate.
  • Bucket sort by frequency: Because any word's count lies between 1 and total word tokens N, you can group words by frequency in O(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 the U tuples around random pivots to isolate the k smallest in linear average time, then sorts just those k winners.

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 P temporary disk buckets via hash(word) % P so 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-memory Counter to obtain exact global totals for that bucket's words while maintaining a single size-k heap across all P buckets. 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 in O(1) RAM, though sorting costs O(N log N) disk work compared to O(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 reducer hash(word) % R so one reducer receives every subtotal for a given word, sums its exact frequency, and keeps only its local top k in a size-k heap. Finally, a single coordinator merges the R * k finalists from all reducers in O(R * k log k) time to emit the global top k.
  • 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 w grid of integer counters (w = ceil(e / epsilon), d = ceil(ln(1 / delta))) indexed by d independent hash functions: each token increments one cell per row, and querying the minimum across those d cells never undercounts and overcounts by at most epsilon * N with probability 1 - delta (using ~54 KB of RAM for epsilon = 0.001, delta = 0.01), paired with a size-k candidate heap. Alternatively, the Space-Saving summary tracks m explicit (word, count) counters and replaces the minimum-count entry when a new word arrives, guaranteeing deterministic count error <= N / m and retaining every word whose true count exceeds N / 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 the epsilon * N (or N / m) error margin.

Follow-up questions

Similar questions

More Box interview questions

All 9 Box questions →