Problem overview
The method wordFrequency receives a string, sentence, and returns an object that maps each word to the number of times it appears. The words are lowercase, separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.
For "the cat and the hat" the result is {"the": 2, "cat": 1, "and": 1, "hat": 1}. For "go go go" it is {"go": 3}: the same word three times is one key with the value 3. A sentence of one word, "hello", gives {"hello": 1}.
Approach
There are two jobs. First, turn the sentence into an array of words. Then count the words with the same pattern as counting letters: an object that starts empty, a pass over the array, and for each word either an increment or a first entry with the value 1.
The first job is sentence.split(" "). It cuts the string at every space and returns the pieces as an array, so "the cat and the hat" becomes ["the", "cat", "and", "the", "hat"].
Tracing "the cat and the hat": "the" is new and gets 1, then "cat" and "and" get 1 each. The second "the" is already a key, so its count goes from 1 to 2. "hat" is new. The final object is {"the": 2, "cat": 1, "and": 1, "hat": 1}. Words are only added to the object, never removed, so every word of the sentence ends up as a key.
This is the same counting pattern as counting the letters of a word. The only change is what you loop over: the pieces from split instead of the characters of a string.
Step by step
- Split the sentence. Store
sentence.split(" ")inwords, astring[]. - Create the dictionary.
countsis an empty object of the type{ [key: string]: number }. - Loop over the words with
for...of. Each word adds 1 to its own count. - Known word. If
word in counts, add 1 tocounts[word]. - New word. Otherwise set
counts[word]to 1. A missing key reads asundefined, andundefined + 1isNaN, so a new word can't start by being incremented. - Return
countsafter the loop.
The solution in TypeScript
class Solution {
wordFrequency(sentence: string): { [key: string]: number } {
const words: string[] = sentence.split(" ");
const counts: { [key: string]: number } = {};
for (let word of words) {
if (word in counts) {
counts[word] += 1;
} else {
counts[word] = 1;
}
}
return counts;
}
}
Details worth knowing:
split(" ")splits at every single space. That is exactly right when words are separated by single spaces, as here. With two spaces in a row,"a b".split(" ")gives["a", "", "b"], and the empty string would be counted as a word. This lesson's sentences don't have double spaces.- Keys are strings. A word is already a string, so it is used as the key as written.
let wordversusconst word. The loop never reassignsword, soconstwould work too. Both pass the lesson's tests.- Plain objects have inherited keys. The
inoperator also finds keys an object gets fromObject.prototype, such astoStringandconstructor. For the sentence"the toString", the code returns{"the":1,"toString":"function toString() { [native code] }1"}, because"toString" in countsis already true on an empty object. The lesson's words are ordinary lowercase words, so the tests don't hit this. For arbitrary text, aMapavoids the problem:counts.has(word)only sees keys you added.
Edge cases and common mistakes
- No first-time branch. Every count would be
NaN. - Splitting on nothing.
split("")cuts into single characters, which counts letters instead of words. - One word.
"hello".split(" ")is["hello"], and the result is{"hello": 1}. - Repeated word.
"to be or not to be"gives{"to":2,"be":2,"or":1,"not":1}.
Testing
"the cat and the hat"gives{"the":2,"cat":1,"and":1,"hat":1}."go go go"gives{"go":3}."hello"gives{"hello":1}."to be or not to be"gives{"to":2,"be":2,"or":1,"not":1}.
