#916

Word Subsets

Medium
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal solution builds a frequency count of all characters needed from words2 and then checks each word in words1 against this count. This reduces redundant checks and speeds up the process.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency count of the maximum occurrences of each character required by all words in words2.
  2. 2Step 2: For each word in words1, create a frequency count of its characters.
  3. 3Step 3: Compare the frequency count of the current word in words1 with the frequency count from words2. If it meets or exceeds all counts, add it to the result.
solution.py15 lines
1from collections import Counter
2
3def wordSubsets(words1, words2):
4    max_count = Counter()
5    for word in words2:
6        count = Counter(word)
7        for char in count:
8            max_count[char] = max(max_count[char], count[char])
9
10    result = []
11    for word1 in words1:
12        count1 = Counter(word1)
13        if all(count1[char] >= max_count[char] for char in max_count):
14            result.append(word1)
15    return result

Complexity note: The time complexity is O(n + m) where n is the total number of characters in words1 and m is the total number of characters in words2. We only traverse each word a couple of times, making this approach efficient.

  • 1Understanding character frequency is key to solving subset problems.
  • 2Using hash maps can significantly reduce the complexity of character counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.