Python 0916.py
class Solution:
def freq(self, word):
result = [0] * 26
for i in word:
abc = ord(i) - ord('a')
result[abc] += 1
return result
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
words2 = set(words2)
mergedB = [0] * 26
for b in words2:
freqB = self.freq(b)
for i in range(26):
mergedB[i] = max(mergedB[i], freqB[i])
result = []
for a in words1:
freqA = self.freq(a)
ok = True
for i in range(26):
if mergedB[i] > freqA[i]:
ok = False
break
if ok:
result.append(a)
return result
Difficulty
and has an acceptance rate of about 56% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines which strings from the first list satisfy the “universal” condition with respect to the second list. A word from the first collection is kept only if it contains, for every letter, at least as many occurrences as the maximum required count among all words in the second collection. The algorithm proceeds in three logical phases: building a per-letter frequency helper, aggregating the strictest letter requirements from the second list, and finally testing each candidate from the first list against those aggregated requirements.
Key Steps
Per-letter frequency helper
The freq method converts a word into a fixed-size integer array of length 26, where each position corresponds to a letter of the English alphabet. For each character the method computes its zero-based index by subtracting the code point of 'a' and increments the appropriate slot.
def freq(self, word):
result = [0] * 26
for i in word:
abc = ord(i) - ord('a')
result[abc] += 1
return result
Because the array size is constant, the method runs in time proportional to the length of the input word and uses only a small, predictable amount of memory.
Consolidating the strictest requirements from the second list
Before evaluating candidates, the algorithm reduces the second list to a single “merged” frequency array. It first eliminates duplicate entries by converting the list to a set, ensuring each distinct word contributes only once to the requirement calculation. For each distinct word, its frequency array is obtained via freq. The algorithm then updates the merged array by taking the element-wise maximum between the current merged values and the newly computed frequencies. This yields, for each letter, the highest count that any word in the second list demands.
words2 = set(words2)
mergedB = [0] * 26
for b in words2:
freqB = self.freq(b)
for i in range(26):
mergedB[i] = max(mergedB[i], freqB[i])
The result, mergedB, represents the minimal letter inventory a candidate must possess to dominate every word in the second collection.
Filtering the first list against the merged requirements
The algorithm iterates over each word in the first list, computes its frequency array, and then checks whether it meets or exceeds the merged requirements for every alphabet position. The check stops early as soon as a deficit is discovered, avoiding unnecessary comparisons for the remaining letters. If a word passes all 26 checks, it is appended to the result list.
result = []
for a in words1:
freqA = self.freq(a)
ok = True
for i in range(26):
if mergedB[i] > freqA[i]:
ok = False
break
if ok:
result.append(a)
return result
The early-exit condition (break) prevents the algorithm from scanning the full alphabet when a violation is already evident, contributing to overall efficiency.
Edge Cases Handled
When the second list is empty, converting it to a set yields an empty collection, leaving mergedB as an array of zeros. Consequently, every word from the first list satisfies the condition, and the algorithm returns the entire first list.
If the first list contains an empty string, its frequency array consists entirely of zeros. The algorithm will only retain this empty string when mergedB also contains zeros for all letters, which occurs precisely when the second list imposes no letter requirements (e.g., an empty second list).
Duplicate entries in the second list are collapsed by the set conversion, ensuring that repeated words do not inflate the required counts beyond what a single occurrence would dictate.
Words composed solely of letters outside the 'a'-'z' range would produce negative or out-of-range indices when ord(i) - ord('a') is evaluated. However, the code implicitly assumes all inputs are lowercase English letters, and within that domain it correctly handles words of any length, including zero length.
When either input list is None (i.e., not provided), the type hints suggest the function expects proper list objects; the code does not attempt to guard against None, but within the intended usage scenario the function operates safely.
Performance Optimizations
The algorithm leverages a constant-size array of 26 integers for all frequency representations, eliminating the overhead of dynamic data structures such as dictionaries. This choice yields fast index-based updates and comparisons.
Deduplication of the second list via set(words2) reduces the number of frequency calculations, especially when the list contains many repeated entries.
The element-wise max operation during the merge phase ensures that each letter’s requirement is updated only when a higher count is encountered, avoiding redundant assignments.
During the candidate validation loop, the early break on the first failing letter prevents the need to examine the remaining 25 positions, which can be significant when many candidates fail early.
Overall, the design confines the dominant work to linear passes over the input strings and fixed-size inner loops, making the solution scalable for large collections of short words.
ELI5 - Simplified Explanation
Imagine a big box with twenty-six little cubbyholes, each one labeled with a letter from the alphabet. This code is like a clever helper that sorts words by counting how many times each letter appears.
To start, the helper looks at all the words in the second group. It wants to find the superstar requirement for every letter. If one word in the second group has three apples and another word has two, the helper remembers that it needs at least three apples to satisfy the collection. It builds a master list showing the biggest number of times each letter is needed by any single word in that group.
Next, the helper visits every word in the first group. It looks inside each word to see what letters it has and how many there are. It compares those numbers to the master list it made earlier. If a word has enough of every letter to cover all the requirements in the master list, the helper keeps that word. It goes through the entire list until it finishes checking every word.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality