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 <= 100
1 <= words[i].length <= 100
words[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
commonCharCnt
as 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
currCharCnt
array - Update
commonCharCnt
such thatcommonCharCnt[i] = currCharCnt[i]
- Now, we return all the characters from
commonCharCnt
where frequency of character is not 0.
Here is the video explanation:
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;
}
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
(2O(26)
count arrays for common and current word.)