Top K Frequent Words
Problem statement
You are given document text in documents. Count the valid words and return both the total number of valid word occurrences and up to k different words ranked by frequency. More frequent words come first. For equal counts, use alphabetical order.
Read each document separately. A token is a consecutive run of ASCII English letters, ending at any other character or the end of the document. Convert each token to lowercase. Every other ASCII character is a separator, and a token cannot continue into the next document.
If filterEnabled is false, count every token. Otherwise, count only tokens found in the supplied lowercase allowedWords list. Repeating a word in that list has no extra effect.
Return a string matrix with exactly two rows:
- Row
0contains one decimal string: the total number of valid token occurrences after lowercasing and filtering. Count repeated occurrences, not just different words. - Row
1contains the ranked words. Return all available different valid words if there are fewer thank, or an empty row if there are none.
If no valid tokens remain, return [["0"],[]]. This two-row format returns both results.
Setting k=1 answers the most-common-word task, and k=3 answers the top-three task. An array of individual lowercase words with filtering disabled preserves the original top-K exercise. After building a solution that fully sorts the words, discuss using a bounded heap when k is much smaller than the number of different words.
Function
topKFrequentWords(documents: String[], k: int, filterEnabled: boolean, allowedWords: String[]) → String[][]Examples
Example 1
documents = ["red","blue","red","green","blue","red"]k = 2filterEnabled = falseallowedWords = []return = [["6"],["red","blue"]]The original word-array case remains unchanged: red appears 3 times and blue 2.
Example 2
documents = ["pear","apple","pear","apple","plum"]k = 2filterEnabled = falseallowedWords = []return = [["5"],["apple","pear"]]Equal counts retain lexical tie order.
Example 3
documents = ["go","go","go"]k = 1filterEnabled = falseallowedWords = []return = [["3"],["go"]]k=1 returns the single most common word.
Example 4
documents = ["red, RED blue.","green red blue"]k = 3filterEnabled = trueallowedWords = ["blue","green"]return = [["3"],["blue","green"]]Normalize and filter before counting. Blue occurs twice and green once; red is excluded.
Constraints
1 <= documents.length <= 100000; documents contain ASCII characters and total at most200000characters.- Every maximal letter token has length at most
30; a document may be empty or contain only delimiters. 1 <= k <= 100000.0 <= allowedWords.length <= 100000; each entry has1..30lowercase English letters, with total allowlist characters at most200000.