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.
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.
Solutions
Solution 1: Counting
Thinking
Scanning every word for each letter is feasible: both the number of words and their lengths are at most \(100\). Repeatedly walking the same alphabet still wastes comparisons.
A letter appears in the answer as many times as its minimum frequency over all words — the intersection of the multisets.
We therefore count the first word, take a pointwise \(\min\) with every later word, and expand the counts. The alphabet has size \(26\), so extra space is constant.
We use an array \(\textit{cnt}\) of length \(26\) to record the minimum number of times each character appears in all strings. Finally, we traverse the \(\textit{cnt}\) array and add characters with a count greater than \(0\) to the answer.
The time complexity is \(O(n \sum w_i)\), and the space complexity is \(O(|\Sigma|)\), where \(n\) is the length of the string array \(\textit{words}\), \(w_i\) is the length of the \(i\)-th string in the array \(\textit{words}\), and \(|\Sigma|\) is the size of the character set, which is \(26\) in this problem.