📖 Scenario: You work at a word game company. You need to group words that are anagrams of each other to help players find word matches quickly.
🎯 Goal: Build a Rust program that groups a list of words into groups where each group contains words that are anagrams of each other.
📋 What You'll Learn
Create a vector of strings called words with the exact words: "eat", "tea", "tan", "ate", "nat", "bat"
Create a mutable hash map called anagram_map to store groups of anagrams
Use a for loop with variable word to iterate over words
Inside the loop, create a sorted string called sorted_word from the characters of word
Insert word into anagram_map using sorted_word as the key
Print the groups of anagrams stored in anagram_map
💡 Why This Matters
🌍 Real World
Grouping anagrams helps in word games, spell checkers, and search engines to find related words quickly.
💼 Career
Understanding hash maps and string manipulation is essential for software engineers working on text processing and data grouping tasks.
Progress0 / 4 steps
1
Create the list of words
Create a vector of strings called words with these exact words: "eat", "tea", "tan", "ate", "nat", "bat"
DSA Rust
Hint
Use let words = vec!["eat", "tea", "tan", "ate", "nat", "bat"]; to create the vector.
2
Create the hash map to group anagrams
Add a mutable hash map called anagram_map that maps String keys to vectors of strings (Vec<&str>) to group the anagrams.
DSA Rust
Hint
Use let mut anagram_map: HashMap> = HashMap::new(); to create the map.
3
Group words by sorted characters
Use a for loop with variable word to iterate over words. Inside the loop, create a sorted string called sorted_word by sorting the characters of word. Then insert word into anagram_map using sorted_word as the key.
DSA Rust
Hint
Use for word in &words to loop. Sort characters with chars.sort_unstable(). Use anagram_map.entry(sorted_word).or_insert(Vec::new()).push(word); to add words.
4
Print the grouped anagrams
Print the groups of anagrams stored in anagram_map using a for loop with variables key and group to iterate over anagram_map.iter(). Print each group vector.
DSA Rust
Hint
Use for (key, group) in anagram_map.iter() and println!("{:?}", group); to print groups.
Practice
(1/5)
1. What is the main idea behind grouping anagrams using a hash map?
easy
A. Use the length of words as keys to group them
B. Store words in a list without any grouping
C. Group words by their first letter only
D. Use sorted strings as keys to group words with the same letters
Solution
Step 1: Understand anagram grouping
Anagrams have the same letters in different orders, so sorting letters gives a common key.
Step 2: Use sorted string as hash map key
By sorting each word and using it as a key, all anagrams map to the same key and group together.
Final Answer:
Use sorted strings as keys to group words with the same letters -> Option D
Quick Check:
Sorted string key groups anagrams [OK]
Hint: Sort each word to find its anagram group key [OK]
Common Mistakes:
Grouping by word length only
Using first letter as key
Not sorting letters before grouping
2. Which Rust code snippet correctly creates a hash map to group anagrams by sorted keys?
easy
A. let mut map: HashMap = HashMap::new();
B. let map = Vec::new();
C. let mut map: HashMap = HashMap::new();
D. let mut map: HashMap = HashMap::new();
Solution
Step 1: Identify correct hash map type
We need keys as sorted strings and values as vectors of strings to hold grouped anagrams.
Step 2: Match Rust syntax for hash map
HashMap correctly maps sorted keys to lists of words.
Final Answer:
let mut map: HashMap = HashMap::new(); -> Option A
Quick Check:
HashMap with String keys and Vec<String> values [OK]
Hint: Use HashMap for grouping anagrams [OK]
Common Mistakes:
Using Vec instead of HashMap
Wrong value type (String instead of Vec<String>)
Incorrect key type (i32 instead of String)
3. What is the output of this Rust code that groups anagrams?
use std::collections::HashMap;
fn group_anagrams(words: Vec<&str>) -> Vec {
let mut map: HashMap = HashMap::new();
for word in words {
let mut chars: Vec<char> = word.chars().collect();
chars.sort_unstable();
let key = chars.into_iter().collect::<String>();
map.entry(key).or_default().push(word.to_string());
}
map.into_values().collect()
}
fn main() {
let input = vec!["eat", "tea", "tan", "ate", "nat", "bat"];
let result = group_anagrams(input);
println!("{:?}", result);
}
medium
A. [["eat", "ate", "tea"], ["tan", "nat"], ["bat"]]
B. [["eat"], ["tea"], ["tan"], ["ate"], ["nat"], ["bat"]]
C. [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
D. [["eat", "tea"], ["tan"], ["ate", "nat"], ["bat"]]
Solution
Step 1: Sort each word to create keys
"eat", "tea", "ate" all sort to "aet"; "tan", "nat" to "ant"; "bat" to "abt".
Step 2: Group words by sorted keys
Words with same sorted key are grouped: ["eat", "tea", "ate"], ["tan", "nat"], ["bat"].
Final Answer:
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]] -> Option C
Quick Check:
Sorted keys group anagrams [OK]
Hint: Sort letters and group words by sorted key [OK]
Common Mistakes:
Not sorting letters before grouping
Grouping single words separately
Mixing order of groups incorrectly
4. Identify the bug in this Rust code for grouping anagrams:
use std::collections::HashMap;
fn group_anagrams(words: Vec<&str>) -> Vec {
let mut map: HashMap = HashMap::new();
for word in words {
let mut chars: Vec<char> = word.chars().collect();
chars.sort(); // Bug here
let key = chars.into_iter().collect::<String>();
map.entry(key).or_default().push(word.to_string());
}
map.into_values().collect()
}
medium
A. Use sort_unstable() instead of sort() for better performance
B. Change chars.into_iter() to chars.iter()
C. Use a HashSet instead of HashMap
D. Convert word to lowercase before sorting
Solution
Step 1: Identify sorting method issue
Using chars.sort() works but sort_unstable() is preferred for primitive types like char for speed.
Step 2: Explain why sort_unstable() is better
sort_unstable() is faster and sufficient here because order stability is not needed for grouping anagrams.
Final Answer:
Use sort_unstable() instead of sort() for better performance -> Option A
Quick Check:
sort_unstable() improves sorting speed [OK]
Hint: Use sort_unstable() for sorting chars in anagrams [OK]
Common Mistakes:
Using sort() unnecessarily slowing code
Changing iterator type incorrectly
Ignoring case sensitivity issues
5. Given a list of words with mixed case and spaces, how would you modify the Rust code to group anagrams correctly ignoring case and spaces?
Example input: ["Listen", "Silent", "en list", "in lets"]
hard
A. Sort letters without any changes to words
B. Convert words to lowercase and remove spaces before sorting letters
C. Use word length as key for grouping
D. Group words by their first character only
Solution
Step 1: Normalize words by removing spaces and converting to lowercase
To group anagrams ignoring case and spaces, clean words by removing spaces and making all letters lowercase.
Step 2: Sort letters of normalized words and use as keys
After normalization, sort letters to get keys that group all anagrams regardless of case or spaces.
Final Answer:
Convert words to lowercase and remove spaces before sorting letters -> Option B
Quick Check:
Normalize words before sorting for correct grouping [OK]
Hint: Lowercase and remove spaces before sorting letters [OK]
Common Mistakes:
Not normalizing case and spaces
Using length or first letter as key
Sorting original words without cleaning
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.