Code Logo

Word Count with Entry API

Published at25 Jul 2026
Rust Collections Medium 3 views
Like0

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

Example 1
Input
[]
Output
[]
Explanation

Empty input

Example 2
Input
["apple","banana","apple"]
Output
[("apple",2),("banana",1)]
Explanation

Count frequencies, sorted by word

Example 3
Input
["x","x","x","x"]
Output
[("x",4)]
Explanation

Same word four times

Example 4
Input
["a","b","c"]
Output
[("a",1),("b",1),("c",1)]
Explanation

All unique, sorted alphabetically

Example 5
Input
["hello","world","hello","hello"]
Output
[("hello",3),("world",1)]
Explanation

Multiple occurrences, sorted by word

Algorithm Flow

Recommendation Algorithm Flow for Word Count with Entry API

Solution Approach

Use the HashMap entry API in Rust for efficient key-based operations. entry() returns an Entry enum with or_insert(), and_modify(), and or_default() for concise insert-or-update.

use std::collections::HashMap;
fn solution(words: Vec<String>) -> HashMap<String, i32> {
  let mut m = HashMap::new();
  for w in words { *m.entry(w).or_insert(0) += 1; }
  m
}

The entry API performs a single lookup per operation. or_insert() inserts a default if absent and returns a mutable reference to the value.

Time O(1) average, Space O(n).

Best Answers

rust - Approach 1
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
}