Skip to content

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: Counters does not exist, it is Counter.
  • 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 Counter for each word, then intersect them.
  • from collections import Counters is a bug; it must be Counter.
  • You do not need to store all counters first; intersect on the fly.
  • count is a bit vague; common is clearer.
from collections import Counter

class Solution:
    def commonChars(self, words: list[str]) -> list[str]:
        counts = []
        for w in words:
            counts.append(Counter(w))
        count = counts[0]
        for c in counts[1:]:
            count = count & c
        return list(count.elements())