Word Count with Entry API
Write a Rust function that uses HashMap's entry() API with or_insert() to count how many times each word appears in a vector of strings. Return the result as a sorted vector of (word, count) tuples. The entry API is Rust's idiomatic way to handle the "insert or update" pattern common in frequency counting.
The entry() method returns an Entry enum representing a slot in the map. The or_insert() method on Entry provides a default value if the key is absent, then returns a mutable reference to the value. By combining these, you can write map.entry(word).or_insert(0) += 1 which either inserts 0 and increments to 1, or increments the existing count. This pattern is more efficient than separate get/insert logic.
The entry API is unique to Rust's HashMap and is considered best practice for frequency counting. It avoids redundant lookups (the key is hashed once) and expresses the intent clearly. The or_insert() method takes ownership of the default value and returns &mut V, allowing direct mutation of the stored value.
Time complexity is O(n * m) where n is the number of words and m is the average word length for hashing. Each entry operation is O(1) amortized. Space complexity is O(k) where k is the number of unique words.
Edge cases include empty input vectors, duplicate words at various positions, single occurrences, and ensuring the result is sorted alphabetically for deterministic output.
Example Input & Output
Empty input
Count frequencies, sorted by word
Same word four times
All unique, sorted alphabetically
Multiple occurrences, sorted by word
Algorithm Flow

Solution Approach
Best Answers
fn solution(words: Vec<String>) -> Vec<(String, i32)> {
let mut map = std::collections::HashMap::new();
for w in words {
*map.entry(w).or_insert(0) += 1;
}
let mut result: Vec<(String, i32)> = map.into_iter().collect();
result.sort();
result
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
