Problem overview
The function word_frequency receives a string, sentence, and returns a HashMap<String, i32> that maps each word to how many times it appears. The words are lowercase and separated by single spaces, and there is at least one word. The order of the entries doesn't matter.
For "the cat and the hat" the map holds the: 2, cat: 1, and: 1 and hat: 1. For "go go go" it holds a single entry, go: 3.
Approach: split, then count
The work has two parts. First, cut the sentence into words. Second, count them with a counting dictionary: for each word, if it is already a key add 1 to its count, otherwise insert it with a count of 1. One pass over the words builds the result.
Step by step
- Split the sentence.
sentence.split(" ")cuts at every space, andcollect()gathers the pieces into aVec<&str>namedwords. - Create the empty map
counts, a mutableHashMap<String, i32>. - Loop over the words, each one called
word. - Known word: if
contains_key(word)is true, insertword.to_string()withcounts[word] + 1. - New word: otherwise insert it with 1.
- Return
countsafter the loop.
The solution in Rust
impl Solution {
fn word_frequency(sentence: String) -> HashMap<String, i32> {
let words: Vec<&str> = sentence.split(" ").collect();
let mut counts: HashMap<String, i32> = HashMap::new();
for word in words {
if counts.contains_key(word) {
counts.insert(word.to_string(), counts[word] + 1);
} else {
counts.insert(word.to_string(), 1);
}
}
return counts;
}
}
The Rust details worth a closer look:
&strandString. The pieces fromsplitare&strslices that borrow fromsentence; nothing is copied yet. The map's keys must own their text, soword.to_string()makes an ownedStringwhen a word is inserted.- Lookups with a
&str. AHashMap<String, i32>can be searched with a&str, socontains_key(word)andcounts[word]work without building aStringfirst. - Indexing panics on a missing key.
counts[word]is safe only inside the branch wherecontains_keyreturned true. - Iterating
words. The loop goes over the vector itself, and each item is a&str, which is cheap to copy. The vector can't be used afterwards. - Shorter form.
*counts.entry(word.to_string()).or_insert(0) += 1;replaces the wholeifandelse.
Tracing "the cat and the hat"
Splitting gives five pieces: the, cat, and, the, hat. The first four are new keys, each inserted with 1. The second the is already a key, so its entry is replaced with 2. hat is new. The map ends with the: 2 and three words with 1.
The cost is proportional to the number of words: splitting is one pass over the text, and each word needs one lookup and one insertion, each constant time on average. The map holds one entry per different word.
Edge cases and common mistakes
- Extra spaces.
split(" ")cuts at every single space. For"a b", with two spaces, it yields"a", an empty string and"b", so the map gets an entry for the empty word. The lesson guarantees single spaces. For messy input,split_whitespace()skips the empty pieces. - One word.
"hello"has no space, sosplityields the whole string and the map ishello: 1. - Indexing a new word. Using
counts[word] + 1without the check panics the first time a word appears. - Uppercase.
"The"and"the"would be different keys. The lesson's words are all lowercase.
Testing
Sorted by word, the entries are:
"the cat and the hat"givesand: 1,cat: 1,hat: 1,the: 2."go go go"givesgo: 3."hello"giveshello: 1.
