Find Common Characters (LeetCode 1002): Solution and Explanation
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
- Create
common, 26 entries, all set to infinity. - For each word, count its letters into a fresh 26-entry
freqarray. - For every letter c, set
common[c] = min(common[c], freq[c]). - After all words, add each letter to the result
common[c]times.
Step-by-step example
words = ["bella","label","roller"]
- "bella" has a:1, b:1, e:1, l:2. These become the starting counts, and every other letter drops to 0.
- "label" also has a:1, b:1, e:1, l:2, so nothing drops.
- "roller" has no 'a' and no 'b', so those drop to 0. It has e:1 and l:2, so they stay.
- 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 result1class Solution {
2 public List<String> commonChars(String[] words) {
3 int[] common = new int[26];
4 Arrays.fill(common, Integer.MAX_VALUE);
5 for (String word : words) {
6 int[] freq = new int[26];
7 for (char ch : word.toCharArray()) {
8 freq[ch - 'a']++;
9 }
10 for (int c = 0; c < 26; c++) {
11 common[c] = Math.min(common[c], freq[c]);
12 }
13 }
14 List<String> result = new ArrayList<>();
15 for (int c = 0; c < 26; c++) {
16 for (int k = 0; k < common[c]; k++) {
17 result.add(String.valueOf((char) ('a' + c)));
18 }
19 }
20 return result;
21 }
22}1class Solution {
2public:
3 vector<string> commonChars(vector<string>& words) {
4 vector<int> common(26, INT_MAX);
5 for (const string& word : words) {
6 vector<int> freq(26, 0);
7 for (char ch : word) {
8 freq[ch - 'a']++;
9 }
10 for (int c = 0; c < 26; c++) {
11 common[c] = min(common[c], freq[c]);
12 }
13 }
14 vector<string> result;
15 for (int c = 0; c < 26; c++) {
16 for (int k = 0; k < common[c]; k++) {
17 result.push_back(string(1, 'a' + c));
18 }
19 }
20 return result;
21 }
22};Time and space complexity
O(n * L)
Each of the n words of length up to L is counted once, plus a fixed 26-step minimum per word.
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.