Maximum Product Of Word Lengths Problem
Description
LeetCode Problem 318.
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
Constraints:
- 2 <= words.length <= 1000
- 1 <= words[i].length <= 1000
- words[i] consists only of lowercase English letters.
Solution
Approach: Letter Bitmasks
We have to look at every pair of words, so the work that matters is the check "do these two words share a letter?". Comparing the letters directly costs up to the length of the words for each pair. Since there are only 26 letters, we can precompute, for each word, a 26-bit mask in which bit c is set when letter c appears in the word.
- For each word, start with
mask = 0and set1 << (letter - 'a')for every letter. - For every pair
i < j, the words share no letter exactly whenmasks[i] & masks[j] == 0. Thenlen(words[i]) * len(words[j])is a candidate. - Return the largest candidate, or 0 when no pair qualifies.
The mask throws away how often a letter appears, which is fine because only "appears or not" matters: "aaa" and "a" have the same mask, and both conflict with any word containing a.
Example: "abcw" has mask with bits a, b, c, w, and "xtfn" has bits x, t, f, n. Their AND is 0, so 4 * 4 = 16 is a candidate.
Complexity: O(n2 + L) time, where n is the number of words and L is the total number of letters: building the masks reads every letter once, and each pair is checked in O(1). O(n) space for the masks.
class Solution:
def maxProduct(self, words: List[str]) -> int:
# masks[i] has bit c set when letter c appears in words[i].
masks = []
for word in words:
mask = 0
for letter in word:
mask |= 1 << (ord(letter) - ord("a"))
masks.append(mask)
best = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
if masks[i] & masks[j] == 0: # no letter in common
best = max(best, len(words[i]) * len(words[j]))
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.