1002. Find Common Characters
On LeetCode ->Reformulated question¶
Return all lowercase letters that appear in every word, keeping duplicates.
Compact 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 this question 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.
Solve the problem with idiomatic python¶
from collections import Counter
class Solution:
def commonChars(self, words: list[str]) -> list[str]:
# Start with counts from the first word.
common = Counter(words[0])
# Keep only the minimum count seen in every word.
for word in words[1:]:
common &= Counter(word)
# Expand counts back into a flat list of characters.
return list(common.elements())
Pytest test¶
import pytest
@pytest.mark.parametrize(
("words", "expected"),
[
(["bella", "label", "roller"], ["e", "l", "l"]),
(["cool", "lock", "cook"], ["c", "o"]),
(["a"], ["a"]),
(["abc", "abc", "abc"], ["a", "b", "c"]),
(["ab", "ba", "a"], ["a"]),
(["zzz", "zz", "zzzz"], ["z", "z"]),
(["abc", "def", "ghi"], []),
],
)
def test_common_chars(words, expected):
assert sorted(Solution().commonChars(words)) == sorted(expected)
Comment 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.