Number of Valid Words for Each Puzzle — LeetCode 1178 Python Solution
HardBit ManipulationTrieArrayHash TableString
- Problem
- #1178
- Pattern
- Trie
- Reading time
- 4 min
- Source
- leetcode.com
The problem
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle.
Example
- 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"
Python solution
Python
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
cnt = Counter()
for w in words:
mask = 0
for c in w:
mask |= 1 << (ord(c) - ord("a"))
cnt[mask] += 1
ans = []
for p in puzzles:
mask = 0
for c in p:
mask |= 1 << (ord(c) - ord("a"))
x, i, j = 0, ord(p[0]) - ord("a"), mask
while j:
if j >> i & 1:
x += cnt[j]
j = (j - 1) & mask
ans.append(x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times |w| + n \times 2^{|p|}) |
| Space | O(m) auxiliary |
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 1178. Number of Valid Words for Each Puzzle is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1178. Number of Valid Words for Each Puzzle?
- LeetCode 1178. Number of Valid Words for Each Puzzle is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1178. Number of Valid Words for Each Puzzle?
- The Python solution on this page runs in O(m \times |w| + n \times 2^{|p|}).
- What is the space complexity of LeetCode 1178. Number of Valid Words for Each Puzzle?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 1178. Number of Valid Words for Each Puzzle cover?
- LeetCode 1178. Number of Valid Words for Each Puzzle is tagged Bit Manipulation, Trie, Array, Hash Table and String on LeetCode.