LeetCode Entry
1002. Find Common Characters
Common letters in words
1002. Find Common Characters easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/629
Problem TLDR
Common letters in words #easy
Intuition
We can count frequencies, then choose minimums for each char. Or do the reverse: for each char count minimum count in all words.
Approach
The frequencies code is faster, but the opposite approach is less verbose.
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\), but can be O(n) to hold the result
Code
fun commonChars(words: Array<String>) =
('a'..'z').map { c ->
List(words.minOf { it.count { it == c } }) { "$c" }
}.flatten()
pub fn common_chars(words: Vec<String>) -> Vec<String> {
('a'..='z').map(|c| {
let min_cnt = words.iter().map(|w|
w.chars().filter(|a| *a == c).count()).min();
vec![format!("{c}"); min_cnt.unwrap_or(0)]
}).flatten().collect()
}