Find Common Characters
EasyUpdated: Sep 8, 2025
Practice on:
Problem
Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
Examples
Example 1:
Input: words = ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: words = ["cool","lock","cook"]
Output: ["c","o"]
Constraints
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consists of lowercase English letters.
Solution
Method 1 - Find min number of characters in all words
Here is the approach we can follow:
- Create
commonCharCntas common character frequency map, which is an int array of 26 characters, as we have to take care of only lower case alphabets. - Now, for each word we calculate the frequency map for it say in
currCharCntarray - Update
commonCharCntsuch thatcommonCharCnt[i] = currCharCnt[i] - Now, we return all the characters from
commonCharCntwhere frequency of character is not 0.
Here is the video explanation: <div class="youtube-embed"><iframe src="https://www.youtube.com/embed/G8X3-p8eixo" frameborder="0" allowfullscreen></iframe></div>
Code
Java
class Solution {
public List<String> commonChars(String[] words) {
int[] commonCharCnt = new int[26];
Arrays.fill(commonCharCnt, Integer.MAX_VALUE);
for (String word: words) {
int[] currCharCnt = new int[26];
word.chars().forEach(character -> ++currCharCnt[character - 'a']);
for (int i = 0; i < 26; i++) {
commonCharCnt[i] = Math.min(commonCharCnt[i], currCharCnt[i]);
}
}
List<String> commonChars = new ArrayList<>();
for (char character = 'a'; character <= 'z'; character++) {
String currChar = Character.toString(character);
while (commonCharCnt[character - 'a']--> 0) {
commonChars.add(currChar);
}
}
return commonChars;
}
}
Python
class Solution:
def commonChars(self, words: list[str]) -> list[str]:
# Initialize commonCharCnt with infinity for all 26 lowercase letters
commonCharCnt = [float('inf')] * 26
for word in words:
currCharCnt = [0] * 26
for ch in word:
currCharCnt[ord(ch) - ord('a')] += 1
for i in range(26):
commonCharCnt[i] = min(commonCharCnt[i], currCharCnt[i])
ans = []
for i in range(26):
ans.extend([chr(i + ord('a'))] * commonCharCnt[i])
return ans
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)(2O(26)count arrays for common and current word.)