Problem overview
The function wordFrequency receives a string sentence of lowercase words separated by single spaces and returns an unordered_map<string, int>: each word is a key, and its value is the number of times the word appears. The sentence has at least one word, and the order of the entries doesn't matter.
For "the cat and the hat" the map holds the: 2, cat: 1, and: 1 and hat: 1. For "go go go" it holds one key, go: 3, and for "hello" it holds hello: 1.
Approach: split, then count
The problem has two parts. First, turn the sentence into a list of words. The lesson provides a split() helper for this, which takes a string and returns a vector<string> of the pieces between the spaces. Second, count the words with the usual counting map: a word seen before has its count raised by one, and a new word starts at 1.
Counting is the same idea as counting letters, except that the keys are whole words instead of characters. Once the sentence is a vector of strings, the code doesn't care what the strings mean.
Take "the cat and the hat". The first "the" is new and gets 1, as do "cat" and "and". The second "the" finds its entry and raises it to 2, and "hat" is new. Four keys remain for five words, because the repeated word shares one entry.
The vector of words is a convenience, not a requirement: you could count each word as soon as you cut it out of the sentence. Splitting first keeps the two jobs apart, so the counting loop reads exactly like the one for letters or numbers.
Step by step
- Split the sentence.
split(sentence)returns the words in order, and the result goes into avector<string>namedwords. - Create an empty map.
unordered_map<string, int>namedcounts: no word has been counted yet. - Loop over the words. Each word adds one to its own count, so each gets a turn.
- Known word. If
counts.count(word) > 0, the word already has an entry, andcounts[word] += 1increases it. - New word. In the
elsebranch,counts[word] = 1creates the entry with its first count. - Return the map after the loop.
The solution in C++
class Solution {
public:
unordered_map<string, int> wordFrequency(string sentence) {
vector<string> words = split(sentence);
unordered_map<string, int> counts;
for (string word : words) {
if (counts.count(word) > 0) {
counts[word] += 1;
} else {
counts[word] = 1;
}
}
return counts;
}
};
The C++ details worth knowing:
splitis provided. The lesson supplies it, so you only call it. Standard C++ has no built-in function to split a string on spaces, which is why a helper is needed.countasks without changing the map.counts.count(word)is 1 if the key exists and 0 otherwise. The subscriptcounts[word]instead inserts the key with the value 0 when it is missing, so usecountwhen you only want to check.- Because
[]inserts a zero,counts[word]++alone works. A new key starts at 0 and the increment makes it 1. The lesson writes out both branches to make each case visible. - Keys are compared by content. Two different
stringobjects holding "the" reach the same entry. Case matters, though: the keys "Hi", "hi" and "HI" are three different entries. - The entry order is unspecified. Different runs and implementations may list the entries differently, so compare contents, not printed order.
Using the returned map
To read one word's count, use counts.at("the"), which throws an exception when the word is absent, or check with counts.count("the") first. To go through all the entries, write for (auto &entry : counts): each entry.first is a word and each entry.second its count. The sum of all the counts equals the number of words in the sentence, which is a handy way to check your result.
Complexity
Time: O(w) for w words on average, plus the cost of splitting the sentence and hashing the words, which depends on their length. Each map lookup and update takes constant time on average. Space: O(w), because the vector of words holds every word and the map holds one entry per different word.
Edge cases and common mistakes
- One word.
"hello"gives a single entry with the value 1. - The same word repeated.
"go go go"gives one key, not three. - Resetting a count. Assigning 1 to every word would give each word the count 1. The
elsemakes sure the assignment happens only the first time. - Extra spaces. The lesson promises single spaces. With two spaces in a row, a split that cuts at every single space produces an empty word between them, and the map gets an entry for the empty string. How a helper treats that depends on its implementation, which is why the input is limited.
- Comparing printed text. Since the order of an
unordered_mapvaries, compare keys and values.
Testing
Printed with the entries sorted by key:
"the cat and the hat"givesand: 1, cat: 1, hat: 1, the: 2."go go go"givesgo: 3."Hi hi HI"givesHI: 1, Hi: 1, hi: 1, three separate words.
