You are 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 <= 1001 <= words[i].length <= 100words[i] consists of lowercase English letters.Before attempting this problem, you should be comfortable with:
A character appears in all words only if it exists in every single word. Moreover, if a character appears twice in every word, we can include it twice in our result. The key insight is to track the minimum frequency of each character across all words. We start with the frequency counts from the first word, then for each subsequent word, we reduce each count to the minimum of the current count and that word's count.
cnt of size 26 (for lowercase letters) with large values (or use the first word's counts).curCnt.cnt[c] = min(cnt[c], curCnt[c]).cnt[c] times.class Solution:
def commonChars(self, words: List[str]) -> List[str]:
cnt = Counter(words[0])
for w in words:
cur_cnt = Counter(w)
for c in cnt:
cnt[c] = min(cnt[c], cur_cnt[c])
res = []
for c in cnt:
for i in range(cnt[c]):
res.append(c)
return resWhere is the number of words and is the length of the longest word.
Starting the global frequency array with zeros causes min(0, curCnt[c]) to always be zero. Initialize with a large value or use the first word's counts as the starting point.
The result must include each common character as many times as it appears in all words. Appending each character only once ignores duplicates that appear in every word.
Sign in to join the discussion