Bird
Raised Fist0

Given the following code snippet using bitmask + hash map frequency counting, what is the output for words = ["apple", "plea", "plea"] and puzzles = ["aelwxyz"]?

easy🧾 Code Trace Q3 of Q15
Subsets & Combinations - Number of Valid Words for Each Puzzle
Given the following code snippet using bitmask + hash map frequency counting, what is the output for words = ["apple", "plea", "plea"] and puzzles = ["aelwxyz"]? ```python def findNumOfValidWords(words, puzzles): freq = {} for word in words: mask = 0 for ch in set(word): mask |= 1 << (ord(ch) - ord('a')) if bin(mask).count('1') <= 7: freq[mask] = freq.get(mask, 0) + 1 res = [] for puzzle in puzzles: first = 1 << (ord(puzzle[0]) - ord('a')) count = 0 # Enumerate subsets of puzzle letters excluding first def backtrack(i, mask): nonlocal count if i == len(puzzle): if mask in freq and (mask & first): count += freq[mask] return backtrack(i + 1, mask) backtrack(i + 1, mask | (1 << (ord(puzzle[i]) - ord('a')))) backtrack(1, first) res.append(count) return res print(findNumOfValidWords(["apple", "plea", "plea"], ["aelwxyz"])) ```
A[0]
B[2]
C[1]
D[3]
Step-by-Step Solution
Solution:
  1. Step 1: Compute frequency map

    "apple" and "plea" have masks with letters a,e,l,p; "plea" appears twice, so freq counts 3 total.
  2. Step 2: Enumerate subsets of puzzle letters including first letter 'a'

    All subsets containing 'a' match the words' masks.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    All three words contain 'a' and letters in puzzle [OK]
Quick Trick: Count words with masks subset of puzzle and containing first letter [OK]
Common Mistakes:
MISTAKES
  • Forgetting to include first letter in subsets
  • Counting duplicates incorrectly
Trap Explanation:
PITFALL
  • Candidates often miss that the first letter must be included in subsets, leading to undercounting.
Interviewer Note:
CONTEXT
  • Tests ability to trace bitmask subset enumeration and frequency counting
Master "Number of Valid Words for Each Puzzle" in Subsets & Combinations

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Subsets & Combinations Quizzes