Problem overview
The function letter_count receives a string, word, and returns a HashMap<char, i32> that maps each letter to the number of times it appears. Only letters that occur become keys, and the order of the entries doesn't matter, because a HashMap has no defined order anyway.
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.
Approach: a counting dictionary
Keep a map from letter to count. For every letter of the word, there are two cases. If the letter is already a key, its count goes up by one. If not, this is its first appearance, and it enters the map with a count of 1. One pass over the word fills the whole map.
Step by step
- Create an empty, mutable map typed
HashMap<char, i32>, namedcounts. The lesson already bringsHashMapinto scope. - Loop over
word.chars(). The method yields the characters of the string one at a time, each achar. - Handle a letter seen before. If
contains_key(&letter)is true, insert the letter again withcounts[&letter] + 1. Inserting an existing key replaces its value. - Handle a new letter in the
elsebranch by inserting it with the value 1. - Return
countsafter the loop.
The solution in Rust
impl Solution {
fn letter_count(word: String) -> HashMap<char, i32> {
let mut counts: HashMap<char, i32> = HashMap::new();
for letter in word.chars() {
if counts.contains_key(&letter) {
counts.insert(letter, counts[&letter] + 1);
} else {
counts.insert(letter, 1);
}
}
return counts;
}
}
The Rust details worth a closer look:
- References as keys.
contains_keyand the indexing syntaxcounts[&letter]take a reference to the key, so you write&letter.inserttakes the key itself, and acharis a small value that is copied, soletterremains usable afterwards. - Indexing panics on a missing key.
counts[&letter]is only safe becausecontains_keywas checked first. That is why a new letter must go through theelsebranch and not be indexed. chars()andchar. Acharis a Unicode character, not a byte. For lowercase English letters, that is the letter you expect.- Random order. Printing a
HashMapcan list its entries in a different order from one run to the next. To compare results, sort the entries first. - A shorter form. Rust's
entryAPI does the same job:*counts.entry(letter).or_insert(0) += 1;. The lesson's version spells out each case so the logic is visible.
Tracing "banana"
The map starts empty. The letter b is not a key, so it is inserted with 1. Then a is new and gets 1. n is new and gets 1. The second a is already a key, so it is replaced with 1 + 1 = 2. The second n becomes 2. The last a becomes 3. The final map is b: 1, a: 3, n: 2, and each letter was looked up once per appearance.
Each lookup and insertion takes constant time on average, so the whole function takes time proportional to the length of the word, and the map has at most one entry per distinct letter.
Edge cases and common mistakes
- Indexing before inserting. Writing
counts[&letter] + 1for a letter that isn't in the map panics at run time. - Forgetting the
else. Without it, no letter would ever get its first entry, and the map would stay empty. - Counting once. Inserting the value 1 for every letter, whether or not it was seen, would make every count 1.
- Single letter.
"a"gives a map with one entry,a: 1.
Testing
Sorted by letter, the entries are:
"banana"givesa: 3,b: 1,n: 2."hello"givese: 1,h: 1,l: 2,o: 1."a"givesa: 1.
