⚡Flashcard Drill➔
NeetCode #137LC-916MediumArrays & Hashing
← Back to All Problems

#137 · #916 · Word Subsets(单词子集)

📌 Problem Statement & Constraints

A string a is a subset of string b if every letter of a occurs in b at least as many times. Given words1 and words2, return every word in words1 that is a superset of every word in words2. Constraints: 1 <= words1.length, words2.length <= 10^4, 1 <= word length <= 10.

💡 Core Algorithmic Approaches

  1. Being a superset of all words in words2 is equivalent to being a superset of their maximum character requirements.
  2. Compute, for each character, the maximum count required across all words in words2. Call this the requirement vector.
  3. Then a word of words1 qualifies exactly when its character counts dominate the requirement vector.
  4. This reduces the check from O(|words2|) per word to O(26) per word, which is the key optimisation.

💻 Benchmark Python3 Implementation

class Solution:
    def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
        need = [0] * 26
        for b in words2:
            cnt = [0] * 26
            for ch in b:
                cnt[ord(ch) - 97] += 1
            for i in range(26):
                need[i] = max(need[i], cnt[i])   # strongest requirement per letter
        res = []
        for a in words1:
            cnt = [0] * 26
            for ch in a:
                cnt[ord(ch) - 97] += 1
            if all(cnt[i] >= need[i] for i in range(26)):
                res.append(a)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(total characters of words2 + 26 * |words1| + total characters of words1): the 26-length comparison per word is the dominant constant factor.
💾 Space Complexity
O(1): two 26-length arrays.

⚠️ Interview Pitfalls & Follow-ups

  • Checking each word of words2 separately against each word of words1: O(|words1| * |words2| * 26), far too slow at 10^4 by 10^4.
  • Using the union of characters instead of the maximum counts: multiplicity matters, so words2 = ["ee"] requires two es.
  • Taking the sum of counts across words2 instead of the maximum: a letter required twice in one word and once in another needs a count of 2, not 3.
  • Forgetting that a word must dominate in every letter: the all(...) over all 26 positions is essential.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

单词子集

给你两个字符串数组 words1 和 words2。如果 words1 中的某个字符串 b 满足:words2 中的 每个 字符串都是 b 的子集(即 words2[i] 的每个字符都能在 b 中找到,且出现次数足够),那么称 b 是 通用 的。返回 words1 中所有通用字符串组成的数组。约束:1 ≤ words1.length, words2.length ≤ 10^4;1 ≤ words1[i].length, words2[i].length ≤ 10;所有字符串仅含小写英文字母。

核心要点

  • 先把 words2 压缩成「需求向量」(关键优化) :words2 中每个字符串都必须是候选串的子集,因此对每个字符取 words2 中 所有 字符串的最大需求次数,得到一个长度 26 的需求数组。
  • 为什么可以压缩 :条件「每个 words2[i] 都是 b 的子集」等价于「b 满足所有 words2[i] 需求的逐字符最大值」。
  • 校验 words1 :对每个候选串统计字符频次,若所有字符都满足 count[c] &gt;= need[c] 则它是通用的。
  • 复杂度 :若不压缩,需对每个 words1 元素逐一检查 words2 的全部元素,是 O(|w1| × |w2| × L);压缩后是 O(|w2| × L + |w1| × 26),在本题规模下差别巨大。

常见陷阱

  • 不压缩 words2 而直接两两检查 :对每个 words1 元素都要遍历 words2 的全部元素,复杂度会多一个 |words2| 因子。压缩成「最大需求向量」是本题的核心优化。
  • 对 words2 的需求取「求和」而非「最大值」 :条件要求 每个 words2[i] 都满足,因此取最大值;取和会要求过于严格,把合法答案漏掉。
  • 用集合判断子集 : set(words2[i]) &lt;= set(w) 只检查字符是否存在,无法反映数量需求(如 words2 = ["aa"]、w = "a" 时集合判断会误判为真)。必须比较计数。
  • 忘记 words2 可能含重复字符 :必须逐字符计数,不能简单去重。

参考实现

class Solution:
    def wordSubsets(self, words1: list[str], words2: list[str]) -> list[str]:
        # ① 把 words2 压缩为逐字符的最大需求
        need = [0] * 26
        for w in words2:
            cur = [0] * 26
            for ch in w:
                cur[ord(ch) - 97] += 1
            for i in range(26):
                if cur[i] > need[i]:
                    need[i] = cur[i]

        # ② 校验 words1 中的每个候选
        res = []
        for w in words1:
            cur = [0] * 26
            for ch in w:
                cur[ord(ch) - 97] += 1
            if all(cur[i] >= need[i] for i in range(26)):
                res.append(w)
        return res