Start learning free

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

Group Words by First Letter in Rust: HashMap of Vecs

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a HashMap where each key is a first letter, written as a one-character string, and its value is an array of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the HashMap doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 5
    Ctrl + Enter to check

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Rust, explained

    Problem overview

    The function group_by_first_letter receives a vector of lowercase words and returns a HashMap<String, Vec<String>>. Each key is a first letter, written as a one-character string, and its value is the vector of all the words that start with that letter. Inside a group the words keep their order from words, repeated words appear as often as they occur, and the order of the map's entries doesn't matter.

    For ["dog", "cat", "deer", "cow", "duck"] the result has two groups: "d" holds ["dog", "deer", "duck"] and "c" holds ["cat", "cow"].

    Approach: find the group, then add to it

    For each word, compute its first letter, find the vector stored under that letter, and push the word onto it. The only complication is the first word with a new letter, because its vector doesn't exist yet. Rust's entry API handles both cases in one expression: it returns the existing vector, or inserts an empty one and returns that.

    The loop visits the words in order and pushes each at the end of its group, so every group keeps the original order.

    Step by step

    1. Create the empty map groups, a mutable HashMap<String, Vec<String>>.
    2. Loop over words without &. Each String moves into the loop variable word.
    3. Take the first letter. word[0..1] is a slice of the first byte, and to_string() turns it into an owned String, because the map's keys must own their text.
    4. Push into the group. groups.entry(first).or_insert(Vec::new()) yields the vector for that letter, creating an empty one if needed, and push(word) adds the word to it.
    5. Return groups after the loop.

    The solution in Rust

    impl Solution {
        fn group_by_first_letter(words: Vec<String>) -> HashMap<String, Vec<String>> {
            let mut groups: HashMap<String, Vec<String>> = HashMap::new();
            for word in words {
                let first = word[0..1].to_string();
                groups.entry(first).or_insert(Vec::new()).push(word);
            }
            return groups;
        }
    }
    

    The Rust details worth a closer look:

    • entry and or_insert. entry(key) looks the key up once. or_insert(value) returns a mutable reference to the stored value, inserting the given one first if the key was absent. Calling push on that reference changes the vector inside the map.
    • Slicing by bytes. word[0..1] takes bytes 0 up to 1, not characters. For lowercase a to z, one byte is one letter, so it is the first letter. A word that starts with a multi-byte character such as "é" makes the slice panic, because the cut would fall inside the character. An empty word panics too, since byte 1 is out of bounds. The lesson's words never have either problem. A safer way to get the first character is word.chars().next(), which returns an Option.
    • Order of use. first is built before word moves into push. The slice borrows word only until to_string() has copied it, so the move that follows is allowed.
    • Moving words. Looping over words itself means each word goes into its group without a copy.

    Edge cases and common mistakes

    • Using the map's order. A HashMap has no order, so don't rely on groups coming out in the order the letters first appeared.
    • Replacing instead of pushing. Calling groups.insert(first, vec![word]) would overwrite the group each time and keep only the last word of each letter.
    • Using &words without cloning. The loop would then give &String items, and pushing one onto a Vec<String> would not compile.
    • One word. ["hello"] gives a single group, "h" with ["hello"].
    • Repeated words. Each occurrence is pushed, so duplicates stay in the group.

    Testing

    Sorted by letter, the groups are:

    • ["apple", "banana", "avocado", "blueberry", "cherry"] gives a: ["apple", "avocado"], b: ["banana", "blueberry"], c: ["cherry"].
    • ["dog", "cat", "deer", "cow", "duck"] gives c: ["cat", "cow"], d: ["dog", "deer", "duck"].
    • ["hello"] gives h: ["hello"].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free