Number of Valid Words for Each Puzzle - Problem
Imagine you're creating a word game where players need to match words against puzzle strings! Given a list of words and a list of puzzles, you need to determine how many words are valid for each puzzle.
A word is considered valid for a puzzle if:
- The word must contain the first letter of the puzzle
- Every letter in the word must appear somewhere in the puzzle
Example: If puzzle = "abcdefg", then:
- ✅
"faced"is valid (contains 'a' and all letters f,a,c,e,d are in puzzle) - ✅
"cabbage"is valid (contains 'a' and all letters are in puzzle) - ❌
"beefed"is invalid (missing required first letter 'a') - ❌
"based"is invalid (contains 's' which isn't in puzzle)
Return an array where answer[i] represents the count of valid words for puzzles[i].
Input & Output
example_1.py — Basic Example
$
Input:
words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
›
Output:
[1,1,3,2,4,0]
💡 Note:
For puzzle "aboveyz": only "aaaa" is valid (contains 'a', all letters in puzzle). For "actresz": "asas", "actt", "access", "actor" are valid.
example_2.py — Edge Case
$
Input:
words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
›
Output:
[0,1,3,2,0]
💡 Note:
Most words don't contain required first letters. "aelpsxy" matches all 3 words since they all contain 'a' and use only letters from the puzzle.
example_3.py — Single Character
$
Input:
words = ["a","aa","aaa"], puzzles = ["aabcxyz","babcxyz"]
›
Output:
[3,0]
💡 Note:
First puzzle starts with 'a' so all words match. Second puzzle starts with 'b' but words don't contain 'b', so no matches.
Visualization
Tap to expand
Understanding the Visualization
1
Convert to Binary
Transform each word and puzzle into a binary pattern representing letter presence
2
Check Master Key
Verify the word contains the puzzle's required first letter
3
Validate Subset
Ensure word's letter pattern is a subset of puzzle's pattern
4
Count Matches
Accumulate valid words for each puzzle efficiently
Key Takeaway
🎯 Key Insight: By converting letters to bits and words to bitmasks, we transform expensive string operations into blazingly fast bitwise AND operations, reducing complexity from O(words × puzzles × length) to O(words + puzzles × 2^7).
Time & Space Complexity
Time Complexity
O(W × L + P × 2^min(L,7))
W×L for building Trie + P puzzles × exploring valid subsets (limited by puzzle length)
✓ Linear Growth
Space Complexity
O(W × L)
Trie space proportional to total character count in words
✓ Linear Space
Constraints
- 1 ≤ words.length ≤ 105
- 4 ≤ words[i].length ≤ 50
- 1 ≤ puzzles.length ≤ 104
- puzzles[i].length == 7
- words[i] and puzzles[i] consist of lowercase English letters
- Each puzzles[i] doesn't contain repeated characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code