Maximum Product of Word Lengths
Medium
Topics
Given an array of strings words, return the maximum value of length(words[i]) * length(words[j]) where the two words share no common letters. If no such pair exists, return 0.
Example 1
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: "abcw" and "xtfn" share no letters: 4 * 4 = 16.
Example 2
Input: words = ["a","aa","aaa","aaaa"] Output: 0
Constraints
- 2 <= words.length <= 1000
- 1 <= words[i].length <= 1000
- words[i] consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two words share a letter iff their 26-bit letter masks intersect. A bitmask reduces the "share a letter?" test to a single AND, so comparing all pairs becomes cheap.
Approach
- Build a bitmask per word: set bit
c - 'a'for each letter. - For every pair
(i, j), ifmask[i] & mask[j] == 0they are disjoint. - Track the maximum length product over disjoint pairs.
Dry Run
words [abcw, baz, foo, bar, xtfn, abcdef]
Each word collapses to a 26-bit mask of which letters it contains, and two words
share no letter exactly when the AND of their masks is 0.
abcw bits for a b c w
baz bits for a b z
foo bits for f o
bar bits for a b r
xtfn bits for f n t x
abcdef bits for a b c d e f
abcw & foo = 0 -> 4 x 3 = 12
abcw & xtfn = 0 -> 4 x 4 = 16
answer 16
The masks are computed once, up front, and then every pair test is a single AND.
That is the trade: O(total characters) to build, then O(n^2) pair tests at O(1)
each, instead of comparing letter sets directly.
It works only because the alphabet is 26 lowercase letters, so a whole letter set
fits in one machine integer. That constraint is what the problem is really
testing, and it is worth saying out loud rather than treating the mask as a
generic trick.
Comparing a word against itself looks like a bug and is not: mask & mask is the
mask, which is non-zero for any non-empty word, so the pair fails the disjointness
test anyway. Starting the inner loop at i + 1 saves work rather than fixing
correctness.Complexity
- Time — O(n^2 + total letters): masks are built in linear total time, then all pairs are compared in O(1) each.
- Space — O(n): one integer mask per word.
Common Pitfalls
- Comparing a word against itself is not a bug here, despite looking like one:
mask & maskis the mask itself, which is non-zero for any non-empty word, so the pair is rejected by the overlap test anyway. Thei + 1start saves work rather than fixing correctness. - The bitmask only works because the alphabet is 26 lowercase letters, so a set of letters fits in an int and the disjointness test is one
&. Say that constraint out loud -- it is what the problem is really testing.
Full Solution — all languages
class Solution:
def maxProduct(self, words):
masks=[]
for w in words:
m=0
for c in w:
m|=1<<(ord(c)-97)
masks.append(m)
res=0
for i in range(len(words)):
for j in range(i+1,len(words)):
if masks[i]&masks[j]==0:
res=max(res,len(words[i])*len(words[j]))
return resimport java.util.*;
class Solution {
public int maxProduct(String[] words) {
int n=words.length;
int[] masks=new int[n];
for(int i=0;i<n;i++)for(char c:words[i].toCharArray())masks[i]|=1<<(c-'a');
int res=0;
for(int i=0;i<n;i++)for(int j=i+1;j<n;j++)if((masks[i]&masks[j])==0)res=Math.max(res,words[i].length()*words[j].length());
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxProduct(vector<string>& words) {
int n=words.size();
vector<int> masks(n,0);
for(int i=0;i<n;i++)for(char c:words[i])masks[i]|=1<<(c-'a');
int res=0;
for(int i=0;i<n;i++)for(int j=i+1;j<n;j++)if((masks[i]&masks[j])==0)res=max(res,(int)(words[i].size()*words[j].size()));
return res;
}
};/**
* @param {string[]} words
* @return {number}
*/ var maxProduct = function(words) {
const masks=words.map(w=> {
let m=0;for(const c of w)m|=1<<(c.charCodeAt(0)-97);return m;
})
;
let res=0;
for(let i=0;i<words.length;i++)for(let j=i+1;j<words.length;j++)if((masks[i]&masks[j])===0)res=Math.max(res,words[i].length*words[j].length);
return res;
};