MediumNo. 0916

Word Subsets — LeetCode 916 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

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

PythonSolution
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 ans

Complexity

Time
O(L)where L is the sum of the lengths of all words in `words1` and `words2`
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy
0522Longest Uncommon Subsequence IIMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.