NeetCode #84LC-1002EasyArrays & Hashing
← Back to All Problems#84 · #1002 · Find Common Characters(查找共用字符)
📌 Problem Statement & Constraints
Given an array of strings
words, return an array of all characters that appear in all strings, including duplicates (a character appearing twice in every word is listed twice). Constraints: 1 <= words.length <= 100, 1 <= words[i].length <= 100, lowercase letters.💡 Core Algorithmic Approaches
- Count the characters in each word.
- For each character, the number of times it can appear in the answer is the minimum of its counts across all words.
- Iterate the distinct characters of the first word, compute the minimum count, and append that many copies.
- Iterating only the first word's characters avoids redundant work, since a character absent from the first word cannot be common.
💻 Benchmark Python3 Implementation
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
from collections import Counter
cnts = [Counter(w) for w in words]
res = []
for ch in set(words[0]): # only characters of the first word can qualify
m = min(c[ch] for c in cnts) # 0 if absent from any word
res.extend([ch] * m)
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(total characters): counting each word once plus a constant-size scan over the alphabet.
💾 Space Complexity
O(k) for the counters, k <= 26.
⚠️ Interview Pitfalls & Follow-ups
- Using a set intersection: this loses multiplicity, so a character appearing twice in every word would be listed only once.
- Iterating the whole alphabet instead of the first word: correct but does unnecessary work; iterating
set(words[0])is tighter. - Taking the sum or maximum of the counts: the correct aggregation is the minimum.
- Returning characters instead of strings: the return type is a list of single-character strings, which
extend([ch] * m)produces correctly.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
查找共用字符
给你一个字符串数组 words,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按任意顺序返回答案。约束:1 ≤ words.length ≤ 100;1 ≤ words[i].length ≤ 100;words[i] 由小写英文字母组成。
核心要点
- 逐字符取最小值(标准解) :以第一个字符串的字符计数为初始「公共计数」,依次与后续每个字符串的计数取 逐字符最小值 。
- 为什么是取最小值 :字符 c 在所有字符串中都出现,其次数受限于「出现最少的那一个」,因此公共可用次数就是各字符串中该字符频次的最小值。
- 构造结果 :遍历最终的公共计数表,把每个字符重复其计数值次放入结果列表。
- 注意结果可重复 :例如 words = ["bella", "label", "roller"] 中,公共字符是 "e"、"l"、"l"(l 出现两次),结果必须包含两个 l。
常见陷阱
- 遍历字典时直接删除键 : for c in common 中若删除键会抛 RuntimeError。必须用 list(common) 拷贝键列表,或先收集待删键再统一删除。
- 结果去重 :本题 要求保留重复 (最小频次个),用集合会丢失重复。
- 用集合交集代替计数取 min :集合交集只能得到「出现的字符集合」,无法反映每个字符的可用次数,会漏掉重复字符。
- 忘记 cw[c] 对不存在的键返回 0 :Counter 的默认值为 0,因此 min(common[c], cw[c]) 在 c 不存在时自然得到 0,后续构造结果时该字符贡献 0 个,逻辑正确。
参考实现
from collections import Counter
class Solution:
def commonChars(self, words: list[str]) -> list[str]:
common = Counter(words[0])
for w in words[1:]:
cw = Counter(w)
for c in list(common): # list() 避免遍历中修改字典
common[c] = min(common[c], cw[c])
res = []
for c, v in common.items():
res.extend([c] * v) # 按最小频次重复放入
return res