Largest Letter Coverage from Non-Overlapping Words
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Choose words with no repeated letters that share no letters with each other, maximizing total letters covered; tests bitmask encoding and pruned backtracking.
Largest Letter Coverage from Non-Overlapping Words
You are given a list of words made of lowercase English letters. You want to pick some of the words (possibly none) so that, across everything you pick, no letter shows up more than once.
This means two things must hold for the chosen words:
- Each chosen word must not repeat a letter within itself (so
"aa"can never be chosen). - Any two chosen words must have no letter in common.
Return the largest total number of distinct letters that a valid choice can cover. Because all chosen letters are distinct, this equals the sum of the lengths of the chosen words.
Rules for edge cases:
- Choosing no words is allowed and covers
0letters, so the answer is never negative. - An empty string is allowed in the input and contributes nothing.
- If the same word (or an anagram of it) appears several times, at most one copy can be chosen, since copies share letters.
- All letters are in
atoz.
Input
words: a list of strings.
Output
- An integer: the maximum number of distinct letters covered by a valid selection.
Constraints
0 <= len(words), and the list is small enough that an exponential search with good pruning finishes in time.- Each word consists only of lowercase letters
a-z(possibly empty). - The answer is at most
26.
Examples
Example 1
Input: max_distinct_letters(['un', 'iq', 'ue'])
Output: 4
Example 2
Input: max_distinct_letters(['cha', 'r', 'act', 'ers'])
Output: 6
Example 3
Input: max_distinct_letters(['abcdefghijklmnopqrstuvwxyz'])
Output: 26
Example 4
Input: max_distinct_letters(['aa', 'bb', 'abc', 'cd'])
Output: 3
Hints
Hint 1
Represent each word as a 26-bit integer where bit k is set if the k-th letter appears. A word with a repeated letter can be discarded while building this mask.
Hint 2
Two words can be taken together exactly when the bitwise AND of their masks is zero. The letters covered by a selection is the number of set bits in the combined mask.
Hint 3
Use include/exclude backtracking over distinct masks. To speed it up, sort masks by size descending and stop a branch when the bit count of (used | union of remaining masks) cannot beat the best answer so far.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Turn each word into a 26-bit mask, where bit k is set when the k-th letter of the alphabet occurs in the word.
- While building a mask, if a letter's bit is already set, the word repeats a letter and is discarded.
- Two words are compatible exactly when their masks have a bitwise AND of zero.
- For a set of pairwise-compatible words, the number of letters covered is the number of set bits in the union of their masks, which equals the sum of their individual bit counts.
The task then becomes: pick pairwise-disjoint masks maximizing total set bits. In general this is a set-packing problem, so we use backtracking with include/exclude decisions and a few optimizations:
- Deduplicate masks. Anagrams and repeated words give the same mask, and at most one of them can be chosen. Empty masks add nothing and are dropped.
- Sort by bit count, descending. Large words first tend to produce a strong answer early, which makes pruning effective.
- Suffix-union bound. Precompute
suffix_union[i], the OR of all masks from indexion. From a state(i, used), nothing can cover more than the bit count ofused | suffix_union[i]. If this is not greater than the best answer so far, the branch is abandoned.
The search at index i first records the current coverage as a candidate answer (every partial selection is valid, including the empty one), then tries including candidates[i] if it is disjoint from used, and then tries excluding it.
Why it is correct
- Only words without repeated letters become candidates, and the
used & mask == 0check guarantees disjointness, so every visited state is a valid selection. - Without pruning, include/exclude enumerates every subset of candidates, so every valid selection is reachable.
- The bound is a true upper bound: any completion only adds letters from
suffix_union[i]. Cutting when the bound is at mostbestnever discards a strictly better answer. - Deduplication is safe because identical masks conflict with each other.
beststarts at 0, so the empty selection is handled.
Complexity
Let L be the total length of all words and m the number of distinct non-empty valid masks.
- Preprocessing:
O(L + m log m). - Search:
O(2^m)in the worst case, but pruning and the 26-letter cap make it fast in practice. - Space:
O(m)for the candidates, suffix unions, and recursion depth.
Reference solution
from typing import List
def max_distinct_letters(words: List[str]) -> int:
masks = set()
for word in words:
mask = 0
valid = True
for ch in word:
bit = 1 << (ord(ch) - ord('a'))
if mask & bit:
valid = False
break
mask |= bit
if valid:
masks.add(mask)
candidates = sorted((m for m in masks if m), key=lambda x: bin(x).count("1"), reverse=True)
n = len(candidates)
suffix_union = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suffix_union[i] = suffix_union[i + 1] | candidates[i]
best = 0
def dfs(i: int, used: int, covered: int) -> None:
nonlocal best
if covered > best:
best = covered
if i == n:
return
if bin(used | suffix_union[i]).count("1") <= best:
return
mask = candidates[i]
if not (used & mask):
dfs(i + 1, used | mask, covered + bin(mask).count("1"))
dfs(i + 1, used, covered)
dfs(0, 0, 0)
return best