LeetCode 1178: Number of Valid Words for Each Puzzle Solution
Master LeetCode problem 1178 (Number of Valid Words for Each Puzzle), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1178. Number of Valid Words for Each Puzzle
Problem Explanation
Explanation:
To solve this problem, we need to find the number of valid words for each puzzle based on the given conditions. We can use a bitmask approach to represent each word and puzzle as a bitmask where each bit represents a character (a-z).
- For each word, generate a bitmask where each bit is set if the corresponding character is present in the word.
- For each puzzle, generate a bitmask where the first bit is set for the first character and subsequent bits are set if the corresponding character is present in the puzzle.
- For each subset of the puzzle bitmask (excluding the first bit), check how many words' bitmasks are a subset of the puzzle bitmask.
- Keep track of the counts and return the result.
Time Complexity: O(N * 2^M), where N is the number of words and M is the length of the words. Space Complexity: O(N + M).
:
Solution Code
class Solution {
public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
Map<Integer, Integer> frequency = new HashMap<>();
for (String word : words) {
int mask = 0;
for (char ch : word.toCharArray()) {
mask |= 1 << (ch - 'a');
}
frequency.put(mask, frequency.getOrDefault(mask, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (String puzzle : puzzles) {
int count = 0;
int mask = 0;
for (char ch : puzzle.toCharArray()) {
mask |= 1 << (ch - 'a');
}
int subset = mask;
int first = 1 << (puzzle.charAt(0) - 'a');
while (subset > 0) {
if ((subset & first) > 0 && frequency.containsKey(subset)) {
count += frequency.get(subset);
}
subset = (subset - 1) & mask;
}
result.add(count);
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1178 (Number of Valid Words for Each Puzzle)?
This page provides optimized solutions for LeetCode problem 1178 (Number of Valid Words for Each Puzzle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1178 (Number of Valid Words for Each Puzzle)?
The time complexity for LeetCode 1178 (Number of Valid Words for Each Puzzle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1178 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1178 in Java, C++, or Python.