1002. Find Common Characters
On LeetCode ->Problem¶
Return all lowercase letters that appear in every word, keeping duplicates.
Example:
words = ["bella", "label", "roller"]
common counts:
- e -> min(1,1,1) = 1
- l -> min(2,2,2) = 2
answer = ["e", "l", "l"]
Key trick¶
Count letters in each word, then keep the minimum frequency per letter across all words.
Trap¶
- Forgetting duplicates matter.
- Using set intersection, which loses counts.
- Typo:
Countersdoes not exist, it isCounter. - Mutating the first counter is fine, but be clear about it.
Why is it interesting?¶
It is a small problem that tests whether you see the difference between:
- common distinct letters
- common letters with multiplicity
It is also a clean use of frequency counting and intersection.
Python solution¶
from collections import Counter
class Solution:
def commonChars(self, words: list[str]) -> list[str]:
common = Counter(words[0])
for word in words[1:]:
common &= Counter(word)
return list(common.elements())
Comment on my solution¶
- The idea is correct: use
Counterfor each word, then intersect them. from collections import Countersis a bug; it must beCounter.- You do not need to store all counters first; intersect on the fly.
countis a bit vague;commonis clearer.