Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

1178. Number of Valid Words for Each Puzzle

Hard46.9% Acceptance
ArrayHash TableString
Asked by:
D
Dropbox
ProblemHints (3)Solutions (5)VideosCompanies (1)Notes

Problem Statement

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).
Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].

Example 1:

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" 
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.

Example 2:

Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
Output: [0,1,3,2,0]

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] does not contain repeated characters.
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

The key challenge in #1178 Number of Valid Words for Each Puzzle is efficiently checking which words satisfy each puzzle's constraints. A valid word must contain the puzzle’s first letter and use only characters present in the puzzle. A brute-force comparison of every word with every puzzle is too slow, so we need a smarter representation.

A common optimization is to encode each word as a bitmask using 26 bits (one for each letter). Store the frequency of these masks in a hash table. For each puzzle, also build a bitmask and enumerate all possible submasks of its letters that include the first character. Each valid submask corresponds to a set of letters that a word could use. Summing the stored frequencies for these submasks gives the count of valid words.

This approach significantly reduces comparisons because each puzzle has at most 2^6 relevant subsets after fixing the first letter. Some solutions also explore a Trie-based approach, but the bitmask + subset enumeration method is typically simpler and faster.

Complexity

ApproachTime ComplexitySpace Complexity
Bitmask + Subset Enumeration with Hash MapO(W + P * 2^6)O(W)
Trie-based FilteringO(W * L + P * 2^6)O(W * L)

Video Solution Available

NeetCode

View all video solutions

Problem Hints

Use these hints if you're stuck. Try solving on your own first.

1
Hint 1

Exploit the fact that the length of the puzzle is only 7.

2
Hint 2

Use bit-masks to represent the word and puzzle strings.

3
Hint 3

For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask.

Ready to see the solutions?View Solutions

Solutions (5)

Bitmask Approach

Utilize bitmasks to represent words and puzzles. This allows for quick inclusion checks (using bitwise AND) and processing of the large dataset efficiently.

We construct a bitmask for each word and store it in a dictionary with counts. For each puzzle, generate all possible submasks (the example uses a different method) and check if they are present in the preprocessed dictionary.

Time Complexity: O(W + P * 27), where W is the number of words and P is the number of puzzles.
Space Complexity: O(W), due to storing the bitmask of each word.

1def find_num_of_valid_words(words, puzzles):
2    from collections import defaultdict
3    word_count = defaultdict(int)
4    def bitmask(word):
5        bm = 0
6        for char in set(word):
7            bm |= 1 << (ord(char) - ord('a'))
8        return bm
9
10    for word in words:
11        word_count[bitmask(word)] += 1
12
13    results = []
14
15    for puzzle in puzzles:
16        first = 1 << (ord(puzzle[0]) - ord('a'))
17        puzzle_mask = bitmask(puzzle)
18        count = 0
19        submask = puzzle_mask
20
21        while submask:
22            if submask & first:
23                count += word_count[submask]
24            submask = (submask - 1) & puzzle_mask
25
26        results.append(count)
27
28    return results
29
30# Example usage
31words = ["aaaa","asas","able","ability","actt","actor","access"]
32puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
33print(find_num_of_valid_words(words, puzzles))

Explanation

The solution involves the following steps:

  • Create a bitmask for each word that indicates which characters are included.
  • Store these bitmasks in a dictionary (or hashmap) with their occurrence counts.
  • For each puzzle, generate all possible bitmasks that include the first character and check against the stored word bitmasks.

Brute Force Approach

Loop through each puzzle and for each puzzle, check every word in the word list to see if it is valid. This approach is straightforward but inefficient for larger datasets.

Time Complexity: O(W * P * L), where W is the number of words, P is the number of puzzles, and L is the average length of the words.
Space Complexity: O(1), as no additional data structures are used that scale with input size.

1def find_num_of_valid_words(words, puzzles):
2    results = []
3    


Bitmasking with Precomputation

Using a bitmask, we can represent the presence of each letter in a word or puzzle as a single integer. Each bit in this integer corresponds to a letter from 'a' to 'z'.

For each word, compute its bitmask and store it in a hash map with its frequency. When processing puzzles, derive all potential subsets of the puzzle's bitmask that contain the first letter of the puzzle. Use the precomputed hash map to count how many words have matching character sets.

Time Complexity: O(N + P * 2^L), where N is the number of words, P is the number of puzzles, and L is the max number of letters in the puzzle (L = 7), resulting in 2^L subsets.

Space Complexity: O(N) for storing bitmasks and their frequencies.

PythonJavaScript
1def findNumOfValidWords(words, puzzles):    
    
    




Direct Check with Early Stopping

This approach uses direct validation of each word against each puzzle by checking the conditions separately using set operations. Early stopping is applied if any character not in the puzzle is found or if the word doesn't contain the first puzzle character.

Time Complexity: O(P * N * L), where P is the number of puzzles, N is the number of words, and L is the average length of each word.

Space Complexity: O(1) additional space besides input storage.

1import java.util.*;
2
3public class Solution 






Video Solutions

Watch expert explanations and walkthroughs

Valid Sudoku - Amazon Interview Question - Leetcode 36 - Python

NeetCode
13:28391,872 views

Asked By Companies

1 companies
D
Dropbox

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Two SumEasy
Valid SudokuMedium
Sudoku SolverHard
First Missing PositiveHard
More similar problems

Related Topics

ArrayHash TableStringBit ManipulationTrie

Problem Stats

Acceptance Rate46.9%
DifficultyHard
Companies1

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Number of Valid Words for Each Puzzle asked in FAANG interviews?

Yes, this type of problem is common in top tech interviews because it tests bit manipulation, hashing, and optimization techniques. It evaluates a candidate's ability to transform strings into efficient representations and reduce brute-force complexity.

What data structure is best for Number of Valid Words for Each Puzzle?

A hash table combined with bitmask encoding works best for this problem. The hash map stores frequencies of word masks, allowing quick lookup when evaluating puzzle subsets. Some alternative solutions use a Trie, but the bitmask approach is generally simpler and faster.

What is the optimal approach for Number of Valid Words for Each Puzzle?

The most efficient approach uses bit manipulation and a hash map. Words are converted into 26-bit masks and stored with their frequencies, while each puzzle generates valid submasks that include its first letter. By checking these submasks against the map, we can quickly count valid words.

Why is bit manipulation useful in Number of Valid Words for Each Puzzle?

Bit manipulation allows each word and puzzle to be represented as a compact integer mask. This makes subset checks and comparisons extremely fast and enables efficient enumeration of puzzle submasks, reducing the overall computation time.

def
is_valid
(
word
,
puzzle
)
:
4
puzzle_set
=
set
(
puzzle
)
5
return
word
[
0
]
in
puzzle_set
and
all
(
char
in
puzzle_set
for
char
in
word
)
6
7
for
puzzle
in
puzzles
:
8
count
=
0
9
for
word
in
words
:
10
if
is_valid
(
word
,
puzzle
)
:
11
count
+=
1
12
results
.
append
(
count
)
13
14
return
results
15
16
# Example usage
17
words
=
[
"aaaa"
,
"asas"
,
"able"
,
"ability"
,
"actt"
,
"actor"
,
"access"
]
18
puzzles
=
[
"aboveyz"
,
"abrodyz"
,
"abslute"
,
"absoryz"
,
"actresz"
,
"gaswxyz"
]
19
print
(
find_num_of_valid_words
(
words
,
puzzles
)
)

Explanation

Check each word against each puzzle, ensuring the word contains the first letter of the puzzle and no characters not in the puzzle. This approach is easy to understand but computationally expensive.

2
from
collections
import
defaultdict
3
4
def
get_bitmask
(
word
)
:
5
bitmask
=
0
6
for
char
in
word
:
7
bitmask
|
=
(
1
<<
(
ord
(
char
)
-
ord
(
'a'
)
)
)
8
return
bitmask
9
10
word_count
=
defaultdict
(
int
)
11
for
word
in
words
:
12
bitmask
=
get_bitmask
(
word
)
13
word_count
[
bitmask
]
+=
1
14
15
result
=
[
]
16
for
puzzle
in
puzzles
:
17
first
=
1
<<
(
ord
(
puzzle
[
0
]
)
-
ord
(
'a'
)
)
18
puzzle_mask
=
get_bitmask
(
puzzle
)
19
20
subset
=
puzzle_mask
21
count
=
0
22
23
while
subset
:
24
if
subset
&
first
:
25
count
+=
word_count
[
subset
]
26
subset
=
(
subset
-
1
)
&
puzzle_mask
# Get next subset
27
28
result
.
append
(
count
)
29
30
return
result
31

Explanation

This solution first converts each word into a bitmask representing the presence of its characters using a get_bitmask function. The word_count dictionary stores the number of words for each bitmask.

For each puzzle, it generates the bitmask and processes each subset that includes the first puzzle letter using bit manipulation. It checks each subset against precomputed word masks for potential matches and counts them. This avoids unnecessary recomputation and efficiently selects valid words.

{
4
public
List
<
Integer
>
findNumOfValidWords
(
String
[
]
words
,
String
[
]
puzzles
)
{
5
List
<
Integer
>
results
=
new
ArrayList
<
>
(
)
;
6
7
for
(
String
puzzle
:
puzzles
)
{
8
Set
<
Character
>
puzzleSet
=
new
HashSet
<
>
(
)
;
9
for
(
char
c
:
puzzle
.
toCharArray
(
)
)
puzzleSet
.
add
(
c
)
;
10
11
int
count
=
0
;
12
char
firstChar
=
puzzle
.
charAt
(
0
)
;
13
14
for
(
String
word
:
words
)
{
15
if
(
word
.
indexOf
(
firstChar
)
==
-
1
)
continue
;
16
17
boolean
valid
=
true
;
18
for
(
char
c
:
word
.
toCharArray
(
)
)
{
19
if
(
!
puzzleSet
.
contains
(
c
)
)
{
20
valid
=
false
;
21
break
;
22
}
23
}
24
25
if
(
valid
)
count
++
;
26
}
27
28
results
.
add
(
count
)
;
29
}
30
31
return
results
;
32
}
33
}

Explanation

This Java solution leverages set membership tests for characters to ensure each word meets the puzzle's requirements. For each puzzle, it tracks characters in a set and verifies if each word abides by puzzle constraints, including early stopping.

The solution is less efficient for larger input sizes but straightforward to understand and implement directly.