Number of Valid Words for Each Puzzle - Problem
Given an array of words and an array of puzzles, return an array answer where answer[i] is the number of words that are valid with respect to the puzzle puzzles[i].
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).
Input & Output
Example 1 — Basic Case
$
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": word "aaaa" contains 'a' and all letters are in puzzle, so count=1. For "abslute": words "able", "ability", "actt" are valid, so count=3.
Example 2 — Single Letters
$
Input:
words = ["apple","pleas","please"], puzzles = ["aelpxy","aelpxy","aelpsxy"]
›
Output:
[0,1,3]
💡 Note:
"apple" doesn't contain first letter 'a' from puzzle letters only. "pleas" is valid for second puzzle. All three words valid for third puzzle.
Example 3 — No Valid Words
$
Input:
words = ["word","test"], puzzles = ["abcdef"]
›
Output:
[0]
💡 Note:
Neither "word" nor "test" contains 'a' (first letter of puzzle), so no valid words.
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] contains unique characters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of words and array of 7-character puzzles
2
Validation
Check: word contains first char of puzzle + all word chars in puzzle
3
Output
Count of valid words for each puzzle
Key Takeaway
🎯 Key Insight: Use bitmasks to represent character sets for O(1) subset checking instead of character-by-character comparison
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code