Pick Non-Overlapping Words to Cover the Most Letters
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Choose a subset of words with no shared letters so the number of distinct letters covered is maximal, which suits bitmask encoding and subset search.
You are given a list of lowercase words. Select any group of words (possibly none) such that no letter appears in more than one selected word. Return the largest possible number of distinct letters covered by a valid selection.
Rules
- Two selected words conflict if they have at least one letter in common. A valid selection contains no conflicting pair.
- A word's contribution is its number of distinct letters. A word with a repeated letter, such as
"aba", is still allowed and counts as the letter set{a, b}, so it contributes 2. - Selecting nothing is valid and scores 0, so an empty input list returns 0.
- If the same word appears twice in the list, the two copies conflict, so at most one of them can be chosen.
- Return a single integer.
Constraints
0 <= len(words) <= 161 <= len(words[i]) <= 26- Every word consists only of lowercase English letters (
atoz).
Examples
Example 1
Input: max_distinct_letters(['abc', 'ade', 'efg'])
Output: 6
Example 2
Input: max_distinct_letters(['ab', 'bc', 'cd'])
Output: 4
Hints
Hint 1
Only 26 letters exist, so each word can be reduced to a 26-bit integer whose set bits mark the letters it contains. Repeated letters collapse automatically.
Hint 2
Two words share no letter exactly when the bitwise AND of their masks is zero. Keep a running OR of the chosen masks and test each new word against it.
Hint 3
With at most 16 words there are at most 65,536 subsets. For each word, branch into skip or take (take only if it does not overlap the used letters), and track the best total of distinct letters.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since there are only 26 letters, each word can be stored as a 26-bit integer, where bit i is set if the word contains the i-th letter of the alphabet. Duplicate letters inside a word collapse naturally, so "aba" and "ab" get the same mask.
Two words share no letter exactly when mask_a & mask_b == 0. So we keep used, the OR of all masks chosen so far, and a new word can be added only if used & mask == 0.
With at most 16 words there are at most 2^16 subsets, so we can explore them all with include/exclude recursion. At each index we either:
- skip the word, or
- take it, if it does not overlap
used, adding its number of distinct letters (the popcount of its mask) to the running total.
When all words have been decided, we update the best total.
Why it is correct
- Every subset of words is reachable by some sequence of skip/take choices. The take branch is cut only when the word overlaps already chosen letters, and any subset containing that combination is invalid anyway, so no valid subset is missed.
usedis the union of all chosen masks, so passing theused & mask == 0test means the new word is disjoint from every earlier chosen word. Hence every explored selection is pairwise disjoint.- Chosen masks are pairwise disjoint, so the number of distinct letters covered equals the sum of the popcounts of the masks. The running total is therefore exactly the quantity being maximised.
- The empty selection scores 0, and
beststarts at 0, so an empty input returns 0. Duplicate words overlap with each other, so only one can be taken.
Complexity
- Time: O(L + 2^n), where L is the total number of characters (for building masks) and n is the number of words. The recursion tree has at most about 2^(n+1) nodes, each doing constant work.
- Space: O(n) for the masks and the recursion depth.
Reference solution
from typing import List
def max_distinct_letters(words: List[str]) -> int:
masks = []
for word in words:
mask = 0
for ch in word:
mask |= 1 << (ord(ch) - ord('a'))
masks.append(mask)
n = len(masks)
best = 0
def search(index, used, total):
nonlocal best
if index == n:
if total > best:
best = total
return
# Skip this word.
search(index + 1, used, total)
# Take this word if it shares no letter with the chosen ones.
mask = masks[index]
if used & mask == 0:
search(index + 1, used | mask, total + bin(mask).count("1"))
search(0, 0, 0)
return best