Word Subsets — LeetCode 916 Python Solution
MediumArrayHash TableString
- Problem
- #916
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity.
Python solution
Python
class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
cnt = Counter()
for b in words2:
t = Counter(b)
for c, v in t.items():
cnt[c] = max(cnt[c], v)
ans = []
for a in words1:
t = Counter(a)
if all(v <= t[c] for c, v in cnt.items()):
ans.append(a)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(L), where L is the sum of the lengths of all words in `words1` and `words2` |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 916. Word Subsets is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 916. Word Subsets?
- LeetCode 916. Word Subsets is rated Medium on LeetCode.
- What is the time complexity of LeetCode 916. Word Subsets?
- The Python solution on this page runs in O(L), where L is the sum of the lengths of all words in `words1` and `words2`.
- What is the space complexity of LeetCode 916. Word Subsets?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 916. Word Subsets cover?
- LeetCode 916. Word Subsets is tagged Array, Hash Table and String on LeetCode.