Maximize Disjoint Letter Coverage
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Find the maximum count of distinct letters that can be collected by picking a mutually disjoint subset of strings.
You are given a list of strings where each string consists exclusively of lowercase English characters ('a' through 'z').
Select a collection of these strings such that no two selected strings share any common characters. Among all valid selections, calculate the maximum possible number of distinct characters that the combined selection can contain.
Note:
- Strings may contain duplicate characters internally; internal duplicates do not prevent a string from being selected.
- An empty selection yields
0distinct characters.
Constraints
0 <= len(strings) <= 201 <= len(strings[i]) <= 26- Every character is a lowercase English letter from
'a'to'z'.
Examples
Example 1
Input: max_unique_characters(['abc', 'def', 'ab'])
Output: 6
Example 2
Input: max_unique_characters(['a', 'b', 'c', 'ab'])
Output: 3
Example 3
Input: max_unique_characters([])
Output: 0
Hints
Hint 1
Since there are only 26 possible lowercase English letters, the set of characters present in any string can be compactly represented as a 26-bit integer (bitmask).
Hint 2
Two strings share a character if and only if the bitwise AND of their respective bitmasks is non-zero.
Hint 3
With at most 20 strings, you can explore all valid selections using recursive backtracking or dynamic programming with memoization.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
-
Bitmask Representation: Because the character set is restricted to the 26 lowercase letters
'a'through'z', we can represent the distinct letters of any string as a 26-bit integer bitmask. Bit $k$ (where $0 \le k < 26$) is set to $1$ if the characterchr(ord('a') + k)appears in the string.- Checking whether two strings share any letters reduces to a simple bitwise AND operation:
mask_a & mask_b != 0. - Combining letter sets uses bitwise OR:
mask_a | mask_b. - The number of unique letters in a mask is given by its popcount (i.e.,
mask.bit_count()).
- Checking whether two strings share any letters reduces to a simple bitwise AND operation:
-
Search Strategy / Dynamic Programming: With $N \le 20$, the maximum number of string subsets is $2^{20} \approx 10^6$. We can use recursive backtracking or dynamic programming with memoization to find the maximum possible bit count.
At each index
iwith current set of taken charactersused:- Option 1: Skip string
i. Recurse tobest(i + 1, used). - Option 2: Take string
i(if(used & masks[i]) == 0). Recurse tomasks[i].bit_count() + best(i + 1, used | masks[i]).
Memoizing on
(index, used)prevents redundant evaluations across different paths that accumulate the same set of characters. - Option 1: Skip string
Complexity
- Time Complexity: $\mathcal{O}(N \cdot L + 2^N)$, where $N$ is the number of strings and $L$ is the maximum length of a string. Converting strings to bitmasks takes $\mathcal{O}(N \cdot L)$. Since $N \le 20$, the state space for the dynamic programming recursion is at most $2^N$ states, each doing $\mathcal{O}(1)$ bitwise operations.
- Space Complexity: $\mathcal{O}(N + 2^N)$ for the recursion call stack and memoization cache.
Python 3 Implementation
from functools import lru_cache
from typing import List
def max_unique_characters(strings: List[str]) -> int:
masks = []
for s in strings:
mask = 0
for ch in s:
mask |= 1 << (ord(ch) - ord('a'))
masks.append(mask)
n = len(masks)
@lru_cache(maxsize=None)
def best(index: int, used: int) -> int:
if index == n:
return 0
result = best(index + 1, used)
mask = masks[index]
if used & mask == 0:
result = max(result, mask.bit_count() + best(index + 1, used | mask))
return result
return best(0, 0)