File: find-words-that-can-be-formed-by-characters/solution.py

Date: 2026-06-06

Time: 16:49

find-words-that-can-be-formed-by-characters/solution.py

Purpose

Solves LeetCode 1160 — Find Words That Can Be Formed by Characters. Given a list of words and a string of available characters, it returns the total length of all words that can be spelled using the available characters, where each character can be used at most once per word.

Key Components

Solution.countCharacters(words, chars) -> int — The single method. It takes a list of candidate words and a character pool, and returns the sum of lengths of all "good" words (words whose character requirements are a subset of the pool).

Patterns

The solution uses Counter subtraction as a set-containment check. Counter(word) - chars_count produces a Counter with only the positive remainders — characters needed by the word but not available in chars. If that result is empty (falsy), the word can be formed. This is a well-known Python idiom: Counter subtraction drops zero and negative counts, so not (A - B) is equivalent to "A is a sub-multiset of B."

The entire computation is a single generator expression inside sum(), which avoids intermediate list allocation.

Dependencies

Imports: collections.Counter for frequency counting, typing.List for type hints.

Imported by: The test file at find-words-that-can-be-formed-by-characters/test_solution.py. The large "Imported By" list in the prompt is an artifact of the repo's shared test infrastructure — those other test files don't actually import this solution.

Flow

1. Build a Counter from chars once (O(len(chars))).

2. For each word, build a Counter from the word, subtract the chars Counter, and check if the result is empty.

3. If empty (the word is formable), contribute len(word) to the running sum.

Total complexity: O(n * k) where n is the number of words and k is the average word length. The chars Counter is built once and reused.

Invariants

Error Handling

None. The method trusts its inputs match the LeetCode contract (non-empty strings, lowercase English letters). No validation, no exceptions — appropriate for a competitive programming solution.

Topics to Explore

Beliefs