Find Common Characters (LeetCode 1002): Solution and Explanation

Easy
Array
Hash Table
String

Given a list of lowercase words, return every letter that appears in all of them, repeated as many times as it appears in every word. Any order is accepted.

Intuition

Think about one letter at a time. If 'l' appears 2 times in one word, 2 times in another and 3 times in a third, then only 2 copies of 'l' are shared by all three. The word with the fewest copies sets the limit.

So the answer for each letter is the minimum of its counts across all words. There are only 26 letters, so you can keep one small array of running minimums.

Start every letter at infinity, meaning no word has limited it yet. Each word can only push a count down. A letter missing from any word drops to 0 and never comes back.

Approach: Running minimum of letter counts

  1. Create common, 26 entries, all set to infinity.
  2. For each word, count its letters into a fresh 26-entry freq array.
  3. For every letter c, set common[c] = min(common[c], freq[c]).
  4. After all words, add each letter to the result common[c] times.

Step-by-step example

words = ["bella","label","roller"]
  1. "bella" has a:1, b:1, e:1, l:2. These become the starting counts, and every other letter drops to 0.
  2. "label" also has a:1, b:1, e:1, l:2, so nothing drops.
  3. "roller" has no 'a' and no 'b', so those drop to 0. It has e:1 and l:2, so they stay.
  4. The remaining counts are e:1 and l:2, giving ["e","l","l"].

Code: Python, Java, C++

1class Solution:
2    def commonChars(self, words: List[str]) -> List[str]:
3        common = [float("inf")] * 26
4        for word in words:
5            freq = [0] * 26
6            for ch in word:
7                freq[ord(ch) - ord("a")] += 1
8            for c in range(26):
9                common[c] = min(common[c], freq[c])
10        result = []
11        for c in range(26):
12            result.extend([chr(c + ord("a"))] * common[c])
13        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * L)

Each of the n words of length up to L is counted once, plus a fixed 26-step minimum per word.

Space

O(1)

Two arrays of 26 integers, regardless of input size (not counting the output).

Other approaches

Counter intersection (time O(n * L), space O(1))

In Python, Counter(a) & Counter(b) keeps the minimum count of each key. Folding & over all words gives the same result in one line.

Remove matched characters (time O(n * L^2), space O(L))

Take the first word's letters and, for each other word, remove letters one by one from a copy as you match them. It works but is quadratic in word length.

Common mistakes

  • Starting the running minimum at 0 instead of infinity (or the first word's counts). Every letter would stay at 0.
  • Using a set per word. Sets lose duplicates, but the answer needs letters repeated, like the two 'l's in Example 1.
  • Taking the maximum instead of the minimum. A letter is shared only up to the smallest count.

Frequently asked questions

Does the order of the output matter?

No, any order is accepted. Emitting letters from 'a' to 'z' is just a convenient fixed order.

Why is the space O(1)?

The count arrays always have 26 entries because the input only uses lowercase English letters. Their size does not grow with the number or length of the words.

What happens with a single word?

Every letter of that word is shared with itself, so the answer is all of its characters, with duplicates.