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
- Create an empty map.
unordered_map<char, int>namedcounts: keys are characters, values are integers. - Loop over the characters. A range-based
forover astringvisits onecharper turn, just as it visits the elements of a vector. - Known letter. If
counts.count(letter) > 0, the letter is already a key, socounts[letter] += 1. - New letter. Otherwise,
counts[letter] = 1adds the key with its first count. - 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:
countasks,[]may insert.counts.count(letter)returns 1 if the key exists and 0 if not, and it never changes the map. The subscriptcounts[letter]is different: if the key is missing, it adds it with a default value, which is 0 for anint.- That default makes the
ifoptional. 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_mapkeeps 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
charkey is a single character.'a'in single quotes is achar;"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 usecountto ask without changing the map. - Setting instead of adding. Writing
counts[letter] = 1for 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"givesa: 3, b: 1, n: 2."hello"givese: 1, h: 1, l: 2, o: 1."a"givesa: 1.
