Word Subsets (LeetCode 916): Solution and Explanation
Return every word in words1 that contains each word of words2 as a multiset of letters, counting repeats.
Intuition
The direct check compares every a with every b, which is up to 10^8 pairs at the limits.
The b words never need to be checked one by one. If a has at least as many copies of each letter as the most demanding b asks for, it covers every b at once.
So words2 collapses into 26 numbers: for each letter, the maximum count it has in any single b. Taking the sum instead would over-demand, because different b words can share the same letters of a.
Approach: Per-letter maximum requirement
- Start with need[26] all zero.
- For each b in words2, count its letters and set need[i] = max(need[i], cnt[i]).
- For each a in words1, count its letters.
- Keep a when have[i] >= need[i] for all 26 letters. Return the kept words.
Step-by-step example
words1 = ["warrior","world","error","mirror","worry"], words2 = ["wrr","or","r"]
- "wrr" raises need to w:1, r:2.
- "or" raises o to 1. r stays 2 because 1 < 2.
- "r" changes nothing. Final need: o:1, r:2, w:1.
- "warrior" has w:1, r:3, o:1, so it is kept. "world" has only one r, so it is rejected.
- "error" and "mirror" have no w. "worry" has w:1, o:1, r:2 and is kept.
- Return ["warrior","worry"].
Code: Python, Java, C++
1class Solution:
2 def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
3 need = [0] * 26
4 for b in words2:
5 cnt = [0] * 26
6 for ch in b:
7 cnt[ord(ch) - 97] += 1
8 for i in range(26):
9 need[i] = max(need[i], cnt[i])
10 result = []
11 for a in words1:
12 have = [0] * 26
13 for ch in a:
14 have[ord(ch) - 97] += 1
15 if all(have[i] >= need[i] for i in range(26)):
16 result.append(a)
17 return result1class Solution {
2 public List<String> wordSubsets(String[] words1, String[] words2) {
3 int[] need = new int[26];
4 for (String b : words2) {
5 int[] cnt = new int[26];
6 for (char ch : b.toCharArray()) cnt[ch - 'a']++;
7 for (int i = 0; i < 26; i++) need[i] = Math.max(need[i], cnt[i]);
8 }
9 List<String> result = new ArrayList<>();
10 for (String a : words1) {
11 int[] have = new int[26];
12 for (char ch : a.toCharArray()) have[ch - 'a']++;
13 boolean ok = true;
14 for (int i = 0; i < 26 && ok; i++) if (have[i] < need[i]) ok = false;
15 if (ok) result.add(a);
16 }
17 return result;
18 }
19}1class Solution {
2public:
3 vector<string> wordSubsets(vector<string>& words1, vector<string>& words2) {
4 int need[26] = {0};
5 for (const string& b : words2) {
6 int cnt[26] = {0};
7 for (char ch : b) cnt[ch - 'a']++;
8 for (int i = 0; i < 26; i++) need[i] = max(need[i], cnt[i]);
9 }
10 vector<string> result;
11 for (const string& a : words1) {
12 int have[26] = {0};
13 for (char ch : a) have[ch - 'a']++;
14 bool ok = true;
15 for (int i = 0; i < 26 && ok; i++) if (have[i] < need[i]) ok = false;
16 if (ok) result.push_back(a);
17 }
18 return result;
19 }
20};Time and space complexity
O(A + B)
A and B are the total characters in words1 and words2. Each word also does a fixed 26-step comparison.
O(1)
Two arrays of 26 counts, not counting the output.
Other approaches
Check every pair (time O(n * m), space O(1))
For each a, check each b with letter counts. Correct but O(|words1| * |words2| * 26), too slow at 10^4 each.
Common mistakes
- Summing counts across words2 instead of taking the maximum. With words2 = ["a","a"], a word with a single a is still universal.
- Testing only whether letters are present and ignoring how many copies are needed.
- Re-counting words2 for every a, which brings back the quadratic cost.
Frequently asked questions
Why does the maximum work when there are many b words?
Each b is a subset of a exactly when a meets b's count for every letter. a meets all of them at once exactly when it meets the largest one for each letter, which is need.
Does the order of the output matter?
No. Any order is accepted; this solution returns the words in their words1 order.