Word frequency count
Easy TimeO(n log n) SpaceO(n)
Given a block of text, count how often each word appears in it and return the top three words with their counts, most frequent first. Words are compared without regard to case, so "The" and "the" are one word, and punctuation is not part of a word. Each entry comes back as a pair of the word and its count.
Examples
Example 1
- Input
- text = "the cat and the hat and the bat"
- Output
[["the",3],["and",2],["cat",1]]theappears three times andandtwice;cat,hatandbatappear once each, andcatis the one that keeps third place.
Example 2
- Input
- text = "a b a. B, c"
- Output
- The full stop, the comma and the capital all fold away, so
[["a",2],["b",2],["c",1]]Bis counted as the same word asb.
The Code
function wordFrequency(text) {
const words = text.toLowerCase().split(/[^a-z]+/);
const counts = {};
for (let i = 0; i < words.length; i++) {
const w = words[i];
if (w === "") continue;
counts[w] = (counts[w] || 0) + 1;
}
const pairs = Object.keys(counts).map((w) => [w, counts[w]]);
pairs.sort((x, y) => y[1] - x[1]);
return pairs.slice(0, 3);
}
wordFrequency("the cat and the hat and the bat");Done
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.