Given a string array words, return the maximum value oflength(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.
Solutions
Solution 1: Bit Manipulation
Thinking
A product counts only when two words share no letter. Set intersection is \(O(\sigma)\) per pair; we need a cheaper disjointness test.
Pack each word into a \(26\)-bit mask; bitwise AND zero means disjoint. Check every pair \(i>j\) and keep the max product. \(n\le 1000\) allows \(O(n^2)\).
The problem requires us to find two strings without common letters, so that their length product is maximized. We can represent each string with a binary number \(mask[i]\), where each bit of this binary number indicates whether the string contains a certain letter. If two strings do not have common letters, then the bitwise AND result of the two binary numbers corresponding to these strings is \(0\), that is, \(mask[i] \& mask[j] = 0\).
We traverse each string. For the current string \(words[i]\) we are traversing, we first calculate the corresponding binary number \(mask[i]\), and then traverse all strings \(words[j]\) where \(j \in [0, i)\). We check whether \(mask[i] \& mask[j] = 0\) holds. If it holds, we update the answer to \(\max(ans, |words[i]| \times |words[j]|)\).
After the traversal, we return the answer.
The time complexity is \(O(n^2 + L)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string array \(words\), and \(L\) is the sum of the lengths of all strings in the string array.
Method 1 compares words that share a mask many times. Store the longest word per mask and compare only against seen masks. Duplicate alphabets collapse to one length.