KatInterview

Largest Letter Coverage from Non-Overlapping Words

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationbitmaskbacktrackingset-packing

Last 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 0 letters, 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 a to z.

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.