Start learning free

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

Word Frequency in Rust: Counting Words with a HashMap

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a HashMap 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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Rust, explained

    Problem overview

    The function word_frequency receives a string, sentence, and returns a HashMap<String, i32> that maps each word to how many times it appears. The words are lowercase and separated by single spaces, and there is at least one word. 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 a single entry, go: 3.

    Approach: split, then count

    The work has two parts. First, cut the sentence into words. Second, count them with a counting dictionary: for each word, if it is already a key add 1 to its count, otherwise insert it with a count of 1. One pass over the words builds the result.

    Step by step

    1. Split the sentence. sentence.split(" ") cuts at every space, and collect() gathers the pieces into a Vec<&str> named words.
    2. Create the empty map counts, a mutable HashMap<String, i32>.
    3. Loop over the words, each one called word.
    4. Known word: if contains_key(word) is true, insert word.to_string() with counts[word] + 1.
    5. New word: otherwise insert it with 1.
    6. Return counts after the loop.

    The solution in Rust

    impl Solution {
        fn word_frequency(sentence: String) -> HashMap<String, i32> {
            let words: Vec<&str> = sentence.split(" ").collect();
            let mut counts: HashMap<String, i32> = HashMap::new();
            for word in words {
                if counts.contains_key(word) {
                    counts.insert(word.to_string(), counts[word] + 1);
                } else {
                    counts.insert(word.to_string(), 1);
                }
            }
            return counts;
        }
    }
    

    The Rust details worth a closer look:

    • &str and String. The pieces from split are &str slices that borrow from sentence; nothing is copied yet. The map's keys must own their text, so word.to_string() makes an owned String when a word is inserted.
    • Lookups with a &str. A HashMap<String, i32> can be searched with a &str, so contains_key(word) and counts[word] work without building a String first.
    • Indexing panics on a missing key. counts[word] is safe only inside the branch where contains_key returned true.
    • Iterating words. The loop goes over the vector itself, and each item is a &str, which is cheap to copy. The vector can't be used afterwards.
    • Shorter form. *counts.entry(word.to_string()).or_insert(0) += 1; replaces the whole if and else.

    Tracing "the cat and the hat"

    Splitting gives five pieces: the, cat, and, the, hat. The first four are new keys, each inserted with 1. The second the is already a key, so its entry is replaced with 2. hat is new. The map ends with the: 2 and three words with 1.

    The cost is proportional to the number of words: splitting is one pass over the text, and each word needs one lookup and one insertion, each constant time on average. The map holds one entry per different word.

    Edge cases and common mistakes

    • Extra spaces. split(" ") cuts at every single space. For "a b", with two spaces, it yields "a", an empty string and "b", so the map gets an entry for the empty word. The lesson guarantees single spaces. For messy input, split_whitespace() skips the empty pieces.
    • One word. "hello" has no space, so split yields the whole string and the map is hello: 1.
    • Indexing a new word. Using counts[word] + 1 without the check panics the first time a word appears.
    • Uppercase. "The" and "the" would be different keys. The lesson's words are all lowercase.

    Testing

    Sorted by word, the entries are:

    • "the cat and the hat" gives and: 1, cat: 1, hat: 1, the: 2.
    • "go go go" gives go: 3.
    • "hello" gives hello: 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