Find Common Characters Problem
Description
LeetCode Problem 1002.
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.
Solution
Approach: Minimum Letter Counts
A letter belongs to the answer as many times as it appears in every word, which is the smallest number of times it appears in any single word. For example, l appears twice in "bella", twice in "label" and twice in "roller", so it appears twice in the answer; e appears once in each word, so it appears once.
Keep an array common of 26 counts, one per letter, starting high. For each word, count its letters into a fresh array and set common[i] = min(common[i], count[i]) for every letter. A letter that is missing from some word gets a count of 0 and drops out for good.
At the end, output each letter common[i] times. Duplicates are handled for free by the counts, which is exactly what plain set intersection would get wrong: it would report l only once in example 1.
Complexity: O(total length of all words) time, plus O(26) per word for the minimum. O(1) extra space besides the answer, since the alphabet has 26 letters.
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
common = [len(words[0])] * 26 # common[i]: fewest times letter i appears in any word so far
for w in words:
count = [0] * 26
for ch in w:
count[ord(ch) - ord("a")] += 1
common = [min(a, b) for a, b in zip(common, count)]
return [chr(ord("a") + i) for i in range(26) for _ in range(common[i])]