Start learning free

LESSON 230 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Letter Count in Rust: Counting Characters with a HashMap

Practice Read the full explanation

Given a string word, return a HashMap 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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Rust, explained

    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

    1. Create an empty, mutable map typed HashMap<char, i32>, named counts. The lesson already brings HashMap into scope.
    2. Loop over word.chars(). The method yields the characters of the string one at a time, each a char.
    3. Handle a letter seen before. If contains_key(&letter) is true, insert the letter again with counts[&letter] + 1. Inserting an existing key replaces its value.
    4. Handle a new letter in the else branch by inserting it with the value 1.
    5. Return counts after 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_key and the indexing syntax counts[&letter] take a reference to the key, so you write &letter. insert takes the key itself, and a char is a small value that is copied, so letter remains usable afterwards.
    • Indexing panics on a missing key. counts[&letter] is only safe because contains_key was checked first. That is why a new letter must go through the else branch and not be indexed.
    • chars() and char. A char is a Unicode character, not a byte. For lowercase English letters, that is the letter you expect.
    • Random order. Printing a HashMap can 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 entry API 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] + 1 for 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" gives a: 3, b: 1, n: 2.
    • "hello" gives e: 1, h: 1, l: 2, o: 1.
    • "a" gives a: 1.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free