Start learning free

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

Letter Count in C++: Counting with unordered_map

Practice Read the full explanation

Given a string word, return an unordered_map that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in C++, explained

    Problem overview

    The function letterCount receives a string word and returns an unordered_map<char, int> that maps each letter of the word to the number of times it appears. Only letters that occur become keys, and the order of the entries doesn't matter.

    For "banana" the map holds b: 1, a: 3 and n: 2. For "hello" it holds h: 1, e: 1, l: 2 and o: 1. For "a" it holds just a: 1.

    Approach: a counting map

    A map from letters to counts is the standard way to count things. Walk through the word once. For each letter, either its count already exists and goes up by one, or this is its first appearance and the count starts at 1. When the loop ends, every letter of the word is a key, and each value says how often it appeared.

    The alternative is to scan the word once per distinct letter and count each time, which repeats work. The map does it in one pass: each letter is looked up and updated as you meet it, so you never go back over the word.

    Take "hello". The first l is new and starts at 1. The second l finds the key already there and raises it to 2. Every other letter appears once, so it keeps the 1 it started with. The program prints the finished map as e: 1, h: 1, l: 2, o: 1 when its entries are sorted by key.

    Two details make this pattern work. The key must identify what you count, here the letter itself, so two equal letters always reach the same entry. And the value must start from a known number, here 1 on the first sighting, so every later increase builds on it. The same shape counts words, numbers or any other repeated value.

    Step by step

    1. Create an empty map. unordered_map<char, int> named counts: keys are characters, values are integers.
    2. Loop over the characters. A range-based for over a string visits one char per turn, just as it visits the elements of a vector.
    3. Known letter. If counts.count(letter) > 0, the letter is already a key, so counts[letter] += 1.
    4. New letter. Otherwise, counts[letter] = 1 adds the key with its first count.
    5. Return the map after the loop.

    The solution in C++

    class Solution {
    public:
        unordered_map<char, int> letterCount(string word) {
            unordered_map<char, int> counts;
            for (char letter : word) {
                if (counts.count(letter) > 0) {
                    counts[letter] += 1;
                } else {
                    counts[letter] = 1;
                }
            }
            return counts;
        }
    };
    

    The C++ details worth knowing:

    • count asks, [] may insert. counts.count(letter) returns 1 if the key exists and 0 if not, and it never changes the map. The subscript counts[letter] is different: if the key is missing, it adds it with a default value, which is 0 for an int.
    • That default makes the if optional. Since a missing key starts at 0, counts[letter]++ alone gives the same result. For a new key, [] inserts 0 and then the increment makes it 1. The lesson's version spells out both cases so the logic is visible.
    • The order is not defined. An unordered_map keeps its entries in an order you can't rely on, so two correct maps can print their entries in different orders. Only compare the contents.
    • A char key is a single character. 'a' in single quotes is a char; "a" in double quotes is a string.

    Using the returned map

    Once you have the map, you can look at it in two ways. To ask about one letter, use counts.count('a') to see whether it is there, and counts.at('a') to read its value; at throws an exception for a missing key instead of inserting one. To go through everything, loop over the entries: for (auto &entry : counts) gives pairs whose first is the letter and whose second is the count.

    The loop visits the entries in an unspecified order. If you want a predictable order, for example to print the counts alphabetically, copy the entries into a map, which keeps its keys sorted. That is how the results below were listed.

    Complexity

    Time: O(n) for a word of n letters on average, because each lookup and update in an unordered_map takes constant time on average. Space: O(k), where k is the number of different letters, at most 26 here.

    Edge cases and common mistakes

    • A one-letter word. The result has a single entry with the value 1.
    • Absent letters. A letter that doesn't appear has no entry. Reading counts['z'] on the result would create one with the value 0, so use count to ask without changing the map.
    • Setting instead of adding. Writing counts[letter] = 1 for every letter would lose the earlier counts.
    • Comparing printed output. Because the order varies, check keys and values, not the text of a printed map.

    Testing

    These results come from printing the entries sorted by key:

    • "banana" gives a: 3, b: 1, n: 2.
    • "hello" gives e: 1, h: 1, l: 2, o: 1.
    • "a" gives a: 1.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free