Start learning free

LESSON 224 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Frequency in C++: Counting Words with unordered_map

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return an unordered_map where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in C++, explained

    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

    1. Split the sentence. split(sentence) returns the words in order, and the result goes into a vector<string> named words.
    2. Create an empty map. unordered_map<string, int> named counts: no word has been counted yet.
    3. Loop over the words. Each word adds one to its own count, so each gets a turn.
    4. Known word. If counts.count(word) > 0, the word already has an entry, and counts[word] += 1 increases it.
    5. New word. In the else branch, counts[word] = 1 creates the entry with its first count.
    6. 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:

    • split is 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.
    • count asks without changing the map. counts.count(word) is 1 if the key exists and 0 otherwise. The subscript counts[word] instead inserts the key with the value 0 when it is missing, so use count when 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 string objects 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 else makes 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_map varies, compare keys and values.

    Testing

    Printed with the entries sorted by key:

    • "the cat and the hat" gives and: 1, cat: 1, hat: 1, the: 2.
    • "go go go" gives go: 3.
    • "Hi hi HI" gives HI: 1, Hi: 1, hi: 1, three separate words.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free