Problem 1178

Abstract / Summary

Count how many words match each set of letters in puzzles by checking if all puzzle letters appear in the word.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1178.py

class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
        # helper functions, LAMBDA-MANIA !!!
        ascii = lambda x : ord(x) - ord("a")
        bit   = lambda x : 1 << ascii(x)
        bits  = lambda x : reduce(lambda a, b: a | b, [ bit(c) for c in w ])

        have = defaultdict(int)
        for w in words:
            have[bits(w)] += 1

        # puzzles have at most 7 letters => 2^7
        # but first letter is a must => only 2^6 combinations
        for p in puzzles:
            match  = 0

            prefix = p[0] # first letter always present
            suffix = list(sorted(set([ c for c in p[1:] ]))) # unique letters

            stop = 2 ** len(suffix)
            for m in range(stop): # iterate from 0 to 2^(n - 1)
                mask = bit(prefix)
                for i, s in enumerate(suffix):
                    if m & (1 << i):
                        mask |= bit(s)

                match += have.get(mask, 0)

            yield match
29 lines | 1050 bytes | submitted November 7, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (70k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
  • String
  • Trie
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation defines a Solution class with a single method findNumOfValidWords. The method receives two collections: words, a list of candidate strings, and puzzles, a list of seven-letter strings that act as constraints. For each puzzle the method yields the count of words that satisfy two conditions: the word must contain the puzzle’s first character, and every character of the word must belong to the set of characters appearing in the puzzle. The core technique relies on representing character sets as integer bitmasks, which enables fast set operations and compact storage.

Key Steps

Converting characters to bit positions

ascii = lambda x: ord(x) - ord("a")
bit   = lambda x: 1 << ascii(x)

The two one-line functions map a lower-case letter to its zero-based alphabet index and then to a single-bit integer where that index is set. This representation turns a set of letters into a numeric mask that can be combined with bitwise operators.

Building a mask for each word

bits = lambda w: reduce(lambda a, b: a | b, [bit(c) for c in w])
have = defaultdict(int)
for w in words:
    have[bits(w)] += 1

bits reduces a list of per-character masks into a single mask that records every distinct letter present in the word. The have dictionary aggregates how many words share the same mask, allowing later look-ups to retrieve the total count of words that match a particular letter combination.

Preparing puzzle components

prefix = p[0]                                   # mandatory first letter
suffix = list(sorted(set([c for c in p[1:]])))  # unique remaining letters

The first character of the puzzle is stored separately because it must appear in any valid word. The rest of the puzzle is de-duplicated and sorted, producing at most six distinct letters. Duplicates are ignored, which means puzzles containing repeated letters are handled correctly without inflating the subset enumeration.

Enumerating all admissible subsets

stop = 2 ** len(suffix)
for m in range(stop):
    mask = bit(prefix)
    for i, s in enumerate(suffix):
        if m & (1 << i):
            mask |= bit(s)
    match += have.get(mask, 0)

The loop iterates over every binary pattern of length equal to the number of unique suffix letters. Each pattern m selects a subset of those letters; the mandatory prefix bit is always included. The inner loop builds the mask for the current subset by OR-ing the bits of the chosen suffix letters. The resulting mask is used to query have; if the mask exists, its stored count is added to the running total match.

Producing the result

yield match

Instead of collecting all counts in a list, the method yields each puzzle’s answer as it is computed. This lazy generation reduces peak memory usage when the caller consumes the results incrementally.

Edge Cases Handled

When a puzzle contains repeated characters, the set operation on the suffix removes duplicates, ensuring that the subset enumeration does not consider the same letter more than once. If the puzzle’s suffix is empty (for example, a puzzle like "aaaaaaa" where all characters are identical), len(suffix) becomes zero, stop evaluates to 1, and the loop runs exactly once with a mask that contains only the mandatory first letter. This correctly counts words consisting solely of that single character.

Words that include letters outside the puzzle’s alphabet automatically produce a mask that will never match any generated puzzle mask, because the puzzle masks are built exclusively from the puzzle’s letters. Consequently, such words are excluded without additional checks.

Words containing duplicate letters are collapsed to a single bit per distinct character by the bits function, so the presence of repeated letters in a word does not affect its mask or the counting logic.

Performance Optimizations

The solution’s speed stems from several deliberate choices. Representing character sets as 32-bit integers enables constant-time union and membership tests via bitwise OR and AND. The pre-aggregation of word masks into the have dictionary means each word is processed only once, and subsequent puzzle checks become simple dictionary look-ups.

Limiting the subset enumeration to 2^(len(suffix)) exploits the puzzle constraint that the first letter is mandatory, reducing the combinatorial space from 2^7 to at most 2^6. This reduction is significant because the inner loop runs for every puzzle, and the number of puzzles can be large.

Using defaultdict(int) eliminates the need for explicit existence checks when incrementing word counts, streamlining the construction of the frequency map. The final yield statement avoids building an intermediate list of results, which saves memory when the caller processes the output streamingly.

Overall, the combination of bitmask encoding, pre-counting, and constrained subset generation yields a solution that scales efficiently with the size of the input collections.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big toy chest filled with wooden letter blocks. Each word in the first list is like a special toy made by gluing some of those blocks together. The code starts by turning those words into a secret number code so it can find them very quickly later. Think of this code as a fingerprint that tells the computer exactly which letters are in each toy.

The second list is full of puzzles. Each puzzle is like a playing board that has seven specific letters printed on it. There is one very important rule for these puzzles. The first letter printed on the board must show up in the toy for that toy to be allowed on the board. The other six letters are optional, which means a toy might use them or it might not.

The code looks at every puzzle board one by one. It figures out every possible group of letters that could fit on that board according to the rules. It uses those secret fingerprint numbers to look in the toy chest and count how many toys match the current pattern of letters allowed. By checking all the different combinations of those extra letters, it finds every single toy that is allowed to play on that specific board. After looking at all the possibilities for one puzzle, it announces how many toys were found and then moves on to the next puzzle board to do the same thing again until every board is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.44 | σ = 2.20

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
24 links | 13 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 solutions   November 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality