Number of Valid Words for Each Puzzle — LeetCode 1178 Python Solution

HardBit ManipulationTrieArrayHash TableString
Problem
#1178
Pattern
Trie
Reading time
4 min

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 ans

Complexity

MeasureComplexity
TimeO(m \times |w| + n \times 2^{|p|})
SpaceO(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.

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.

Get Stealth Interview