📖 Scenario: You are working on a simple inventory system for a small bookstore. You want to count how many copies of each book title are currently in stock.
🎯 Goal: Build a Rust program that counts the frequency of each book title using a hash map.
📋 What You'll Learn
Create a vector of book titles with exact values
Create an empty hash map to store frequencies
Use a for loop to count the frequency of each book title
Print the final frequency hash map
💡 Why This Matters
🌍 Real World
Counting frequencies is useful in inventory management, text analysis, and data summarization.
💼 Career
Understanding hash maps and frequency counting is important for software developers working with data processing and algorithms.
Progress0 / 4 steps
1
Create the list of book titles
Create a vector called books with these exact titles: "The Hobbit", "1984", "The Hobbit", "Dune", "1984", "The Catcher in the Rye"
DSA Rust
Hint
Use vec![...] to create the vector with the exact book titles.
2
Create an empty hash map for frequencies
Add a mutable hash map called frequency to store String keys and u32 values. Use std::collections::HashMap::new() to create it.
DSA Rust
Hint
Remember to import std::collections::HashMap at the top.
3
Count the frequency of each book title
Use a for loop with variable book to iterate over books.iter(). Inside the loop, update frequency by increasing the count for each book using entry(book.to_string()).and_modify(|count| *count += 1).or_insert(1).
DSA Rust
Hint
Use books.iter() to loop over references to the book titles.
4
Print the frequency hash map
Print the frequency hash map using println!("{:?}", frequency).
DSA Rust
Hint
The printed hash map may show keys in any order, but the counts must match exactly.
Practice
(1/5)
1. What is the main purpose of using a hash map in the Frequency Counter Pattern?
easy
A. To remove duplicate items from the collection
B. To sort the items in ascending order
C. To count how many times each item appears in a collection
D. To reverse the order of items in the collection
Solution
Step 1: Understand the role of a hash map
A hash map stores key-value pairs, allowing quick lookup of counts for each item.
Step 2: Connect to frequency counting
Using the hash map, we track how many times each item appears by updating counts.
Final Answer:
To count how many times each item appears in a collection -> Option C
Confusing frequency counting with removing duplicates
Assuming hash map reverses order
2. Which of the following Rust code snippets correctly initializes an empty hash map for frequency counting?
easy
A. let mut freq = Vec::with_capacity(10);
B. let freq = Vec::new();
C. let freq = HashSet::new();
D. let mut freq = HashMap::new();
Solution
Step 1: Identify the correct data structure for frequency counting
Frequency counting requires a hash map to store keys and counts.
Step 2: Check Rust syntax for hash map initialization
In Rust, HashMap::new() creates an empty hash map; mut allows modification.
Final Answer:
let mut freq = HashMap::new(); -> Option D
Quick Check:
HashMap::new() initializes empty map [OK]
Hint: Use HashMap::new() with mut for frequency map [OK]
Common Mistakes:
Using Vec or HashSet instead of HashMap
Forgetting mut keyword to modify map
Confusing capacity with initialization
3. What will be the output of the following Rust code?
use std::collections::HashMap;
fn main() {
let items = vec!["apple", "banana", "apple", "orange", "banana", "apple"];
let mut freq = HashMap::new();
for item in items {
let count = freq.entry(item).or_insert(0);
*count += 1;
}
println!("{:?}", freq);
}
medium
A. {"apple": 1, "banana": 1, "orange": 1}
B. {"apple": 3, "banana": 2, "orange": 1}
C. {"apple": 2, "banana": 2, "orange": 2}
D. Compilation error due to missing mut
Solution
Step 1: Count occurrences of each fruit
"apple" appears 3 times, "banana" 2 times, "orange" 1 time in the vector.
Step 2: Check how counts are updated in the hash map
Each item increments its count correctly using entry and or_insert.
Final Answer:
{"apple": 3, "banana": 2, "orange": 1} -> Option B
Quick Check:
Count each fruit correctly = {"apple":3,"banana":2,"orange":1} [OK]
Hint: Count each item incrementally with entry().or_insert(0) [OK]
Common Mistakes:
Assuming counts start at 1 instead of 0
Forgetting to dereference count to increment
Confusing output format or order
4. Identify the error in this Rust code snippet for frequency counting:
use std::collections::HashMap;
fn main() {
let items = vec!["cat", "dog", "cat"];
let mut freq = HashMap::new();
for item in items {
let count = freq.entry(item).or_insert(1);
*count += 1;
}
println!("{:?}", freq);
}
medium
A. or_insert should start with 0, not 1
B. Missing mut keyword for freq
C. Cannot use entry on a vector
D. Dereferencing count is not needed
Solution
Step 1: Understand or_insert initial value
or_insert(1) sets initial count to 1, but counting starts from zero.
Step 2: Effect of starting at 1 on counts
Starting at 1 causes counts to be off by one; correct is or_insert(0).
Final Answer:
or_insert should start with 0, not 1 -> Option A
Quick Check:
Frequency count starts at zero [OK]
Hint: Start counts at 0 with or_insert(0) [OK]
Common Mistakes:
Starting count at 1 inflates frequencies
Forgetting mut on freq (not error here)
Misunderstanding dereference necessity
5. Given a list of words, how would you use the Frequency Counter Pattern with a hash map in Rust to find all words that appear exactly twice?
Choose the best approach.
hard
A. Count frequencies with a hash map, then collect keys with value 2 into a vector
B. Sort the list and pick every second word
C. Use a hash set to store words and print those that appear twice
D. Count frequencies but ignore words appearing more than once
Solution
Step 1: Use hash map to count all word frequencies
Traverse the list, increment counts for each word in the hash map.
Step 2: Filter keys with frequency exactly two
Iterate over the hash map entries and collect words with count == 2.
Final Answer:
Count frequencies with a hash map, then collect keys with value 2 into a vector -> Option A
Quick Check:
Frequency count + filter for 2 = correct approach [OK]
Hint: Count all, then filter keys with count 2 [OK]
Common Mistakes:
Sorting does not guarantee frequency counts
Hash set cannot count duplicates
Ignoring words with frequency > 1 loses needed data
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.