#2085
Easy Algorithms Count common words with one occurrence
Array Hash Table String Counting
73.2% acceptance
Feb 25, 2026
904
21
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn count_words(words1: Vec<String>, words2: Vec<String>) -> i32 {
let mut freq1: HashMap<&str, i32> = HashMap::new();
let mut freq2: HashMap<&str, i32> = HashMap::new();
for w in &words1 {
*freq1.entry(w.as_str()).or_insert(0) += 1;
}
for w in &words2 {
*freq2.entry(w.as_str()).or_insert(0) += 1;
}
freq1.iter()
.filter(|(w, c)| **c == 1 && freq2.get(*w) == Some(&1))
.count() as i32
}
}