#1178

Number of Valid Words for Each Puzzle

Hard
ArrayHash TableStringBit ManipulationTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

The optimal solution uses bit manipulation to represent words and puzzles, allowing for quick checks of character presence. This drastically reduces the time complexity by leveraging the small size of the puzzles.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a bitmask for each word and puzzle, where each bit represents whether a character is present.
  2. 2Step 2: For each puzzle, check the first letter's bit and then use bitwise operations to validate the words.
  3. 3Step 3: Count valid words for each puzzle based on the bitmask comparisons.
solution.py18 lines
1def findNumOfValidWords(words, puzzles):
2    from collections import defaultdict
3    def bitmask(word):
4        mask = 0
5        for char in word:
6            mask |= 1 << (ord(char) - ord('a'))
7        return mask
8    word_masks = [bitmask(word) for word in words]
9    result = []
10    for puzzle in puzzles:
11        first_letter_mask = 1 << (ord(puzzle[0]) - ord('a'))
12        puzzle_mask = bitmask(puzzle)
13        count = 0
14        for word_mask in word_masks:
15            if (word_mask & first_letter_mask) and (word_mask & puzzle_mask) == word_mask:
16                count += 1
17        result.append(count)
18    return result

Complexity note: The time complexity is O(n * m) where n is the number of words and m is the number of puzzles. Each word is processed once to create its bitmask, and each puzzle checks against all word masks. The space complexity is O(n) for storing the word masks.

  • 1Using bit manipulation can significantly speed up checks for character presence.
  • 2The first letter of the puzzle is crucial for determining valid words.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.