Number of Valid Words for Each Puzzle Problem
Description
LeetCode Problem 1178.
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:
wordcontains the first letter ofpuzzle.- For each letter in
word, that letter is inpuzzle.- For example, if the puzzle is
"abcdefg", then valid words are"faced","cabbage", and"baggage", while - invalid words are
"beefed"(does not include'a') and"based"(includes's'which is not in the puzzle).
- For example, if the puzzle is
Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].
Example 1:
Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
Output: [1,1,3,2,4,0]
Explanation:
1 valid word for "aboveyz" : "aaaa"
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
Example 2:
Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
Output: [0,1,3,2,0]
Constraints:
1 <= words.length <= 10^54 <= words[i].length <= 501 <= puzzles.length <= 10^4puzzles[i].length == 7words[i]andpuzzles[i]consist of lowercase English letters.- Each
puzzles[i]does not contain repeated characters.
Solution
Approach: Bitmasks + Subset Enumeration
Whether a word is valid depends only on its set of letters, not on their order or how often they repeat. Encode each set as a 26-bit mask (bit c set when letter c occurs), and count how many words have each mask.
Checking every word against every puzzle is up to 105 * 104 pairs, too slow. Turn it around: a puzzle has only 7 distinct letters, so a valid word's mask must be the puzzle's first letter plus some subset of the other 6 letters. That is just 26 = 64 candidate masks per puzzle; add up the counts of those that occur.
To list the subsets of a mask rest, start with sub = rest and step with sub = (sub - 1) & rest: subtracting 1 clears the lowest set bit and sets all bits below it, and & rest keeps only bits of rest, giving the next smaller subset. Stop after handling sub = 0 (the word whose only letter is the first letter, like "aaaa").
Complexity: O(L + 64 * m) time, where L is the total length of the words and m the number of puzzles, and O(n) space for the mask counts, n being the number of words.
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
def mask_of(word: str) -> int:
mask = 0
for ch in word:
mask |= 1 << (ord(ch) - ord("a"))
return mask
count = {} # letter set (as a bitmask) -> number of words with exactly that set
for w in words:
m = mask_of(w)
count[m] = count.get(m, 0) + 1
answer = []
for p in puzzles:
first = 1 << (ord(p[0]) - ord("a"))
rest = mask_of(p) ^ first
# A valid word's set is the first letter plus any subset of the other six letters.
total, sub = 0, rest
while True:
total += count.get(sub | first, 0)
if sub == 0:
break
sub = (sub - 1) & rest # next smaller subset of rest
answer.append(total)
return answer