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:

  • word contains the first letter of puzzle.
  • For each letter in word, that letter is in puzzle.

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
Valid Words for Each Puzzle ProblemWords:"able""actor""test"Puzzle: "abcdefg"First char: "a"Validation:"able": contains "a" + {a,b,l,e} ⊆ {a,b,c,d,e,f,g} ✓"actor": contains "a" + {a,c,t,o,r} ⊄ {a,b,c,d,e,f,g} ✗"test": missing "a" ✗Output: [1] (only "able" is valid)
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
Asked in
Google 45 Facebook 32 Amazon 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen