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
- Create the empty map
groups, a mutableHashMap<String, Vec<String>>. - Loop over
wordswithout&. EachStringmoves into the loop variableword. - Take the first letter.
word[0..1]is a slice of the first byte, andto_string()turns it into an ownedString, because the map's keys must own their text. - Push into the group.
groups.entry(first).or_insert(Vec::new())yields the vector for that letter, creating an empty one if needed, andpush(word)adds the word to it. - Return
groupsafter 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:
entryandor_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. Callingpushon 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 isword.chars().next(), which returns anOption. - Order of use.
firstis built beforewordmoves intopush. The slice borrowswordonly untilto_string()has copied it, so the move that follows is allowed. - Moving words. Looping over
wordsitself means each word goes into its group without a copy.
Edge cases and common mistakes
- Using the map's order. A
HashMaphas 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
&wordswithout cloning. The loop would then give&Stringitems, and pushing one onto aVec<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"]givesa: ["apple", "avocado"],b: ["banana", "blueberry"],c: ["cherry"].["dog", "cat", "deer", "cow", "duck"]givesc: ["cat", "cow"],d: ["dog", "deer", "duck"].["hello"]givesh: ["hello"].
