Find Maximum Unique-Character Subset
MetaMachine Learning Engineer · OnsiteLast updated
This problem tests your ability to use bitmasking and backtracking with pruning to solve a variation of the maximum set packing problem under character constraints.
Problem Description
Given a list of strings, find a subset of these strings such that the total number of unique characters across all strings in the subset is maximized, under the constraint that no two selected strings can share any common characters. Each character is represented by lowercase English letters 'a' through 'z'.
Return the maximum count of unique characters possible by selecting a disjoint subset of the given strings.
Function Signature
def max_unique_characters(strings: List[str]) -> int:
Constraints
1 <= len(strings) <= 201 <= len(strings[i]) <= 26- All characters are lowercase English letters.
Examples
Example 1:
Input: ["abc", "def", "ab"]
Output: 6
Explanation: We can choose {"abc", "def"} (unique chars: a, b, c, d, e, f; count 6). We cannot include "ab" because it shares 'a' and 'b' with the first string.
Example 2:
Input: ["a", "b", "c", "ab"]
Output: 3
Explanation: We can pick any of {a, b, c} to get 3. The string "ab" cannot be combined with "a" or "b".
Edge Cases
- Empty list of strings should return 0.
- Strings that are identical or contained within each other.
- Strings that are inherently self-disjoint (no repeating characters internally).
Hints
Hint 1
Represent each string as a bitmask of length 26, where each bit corresponds to the presence of a character.
Hint 2
Since the number of strings is small (up to 20), use recursion with backtracking to explore valid combinations of disjoint bitmasks.
Hint 3
Use bitwise AND operations to check if two strings are disjoint and bitwise OR to accumulate the set of unique characters.
Follow-up questions
- How would the solution change if we wanted to maximize the total number of characters (sum of lengths) instead of unique characters?
- If the input size grew to 10,000 strings, how would you optimize the search using a heuristic or pruning strategy?
- What is the time complexity of your backtracking solution in terms of the number of strings N?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.