KatInterview

Maximize Disjoint Letter Coverage

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationbacktrackingdynamic-programming

Last 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 0 distinct characters.

Constraints

  • 0 <= len(strings) <= 20
  • 1 <= 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.