KatInterview

Pick Non-Overlapping Words to Cover the Most Letters

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

Last 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) <= 16
  • 1 <= len(words[i]) <= 26
  • Every word consists only of lowercase English letters (a to z).

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.