Maximum Product of Word Lengths
Pick two words with no letter in common so that their lengths multiply to the largest number.
Given an array of words made of lowercase letters, pick two words that have no letter in common and multiply their lengths. Return the largest product you can get this way. If every pair of words shares at least one letter, return 0.
Example 1
Output: 16
Explanation: "abcw" and "xtfn" share no letters: 4 * 4 = 16.
Example 2
Output: 4
Explanation: "ab" and "cd" share no letters: 2 * 2 = 4.
Example 3
Output: 0
Explanation: every pair shares the letter 'a'.
The Idea
Picture each word as a checklist of the 26 letters, a to z, with a tick next to every letter the word uses. The word "abcw" ticks a, b, c and w, and "xtfn" ticks f, n, t and x. Two words share no letter when no line of the checklist has a tick from both of them.
In Example 1, "abcw" and "xtfn" pass that test, and their lengths give 4 * 4 = 16. Other pairs pass too, such as "abcw" and "foo", but 4 * 3 = 12 is smaller. The longest word, "abcdef", shares a letter with every other word, so it never gets a partner. Solving the problem means asking "do these two words share a letter?" once for every pair. How can that question be quick, however long the words are?
The checklist is the answer. Only which letters a word uses matters, not how often or in what order, so "aaaa" ticks the same single line as "a". A list of 26 yes-or-no answers fits in the bits of one Java intint
The row labelled mask of "abcw" has a 1 at positions 0, 1, 2 and 22, under a, b, c and w, and a 0 everywhere else. To compare two masks, Java's bitwise AND operator, &
In the row labelled mask of "baz", the two orange cells at positions 0 and 1 sit right under the 1s that "abcw" has for a and b. So "abcw" AND "baz" is not 0, and the two words share letters. Two words have no letter in common exactly when the AND of their masks is 0, and that is one operation on two numbers, whether the words have 4 letters or 400.
Solution Approach
Turning that idea into code means settling two things, how to build the mask of a word and how to check the pairs, plus an optional extra for lists with many words made of the same letters.
Building a word's mask
How does a letter become a bit? In Java a charc - 'a'1 << (c - 'a')1 << 22
The bitwise OR operator, |mask |= 1 << (c - 'a')
Could a mask turn out negative? Java stores an int
Checking every pair
Which pairs need checking? Any two words could be the answer, so each pair is tested once. When the AND of the two masks is 0, the product of the two lengths is a candidate, and a variable named best
The simple way skips the masks and compares two words letter by letter, for example by searching the second word for each letter of the first. That costs about the product of the two lengths for every pair, and each word is read again for every partner it is tried with. With masks, each letter is read once while building the masks, and then each pair costs one AND.
Optional: one entry per set of letters
Can there be fewer pairs to test? Words that use the same letters, in any amounts, have the same mask. In Example 3, "a", "aa", "aaa" and "aaaa" all have the mask with only bit 0 set. For a given mask, only its longest word can give the largest product. So a HashMap<Integer, Integer>
Java Solution
The method maxProduct
- First, a helper method,
, builds the mask of one word. It startsletterMask at 0 and, for each charactermask of the word, turns on its bit withc .mask |= 1 << (c - 'a') - In
, a first loop fills an arraymaxProduct with onemasks per word, soint is the mask ofmasks[i] .words[i] - A variable
starts at 0. Two loops, one inside the other, visit every pair: the outer loop movesbest over all the words, and the inner loop movesi over the words after positionj .i - When
is 0, the two words share no letter, andmasks[i] & masks[j] becomes the larger of itself andbest .words[i].length() * words[j].length() - After the last pair, the method returns
, which is still 0 if no pair passed the test.best
The main
public class MaximumProductOfWordLengths {
static int letterMask(String word) {
int mask = 0;
for (char c : word.toCharArray()) {
mask |= 1 << (c - 'a'); // set the bit for this letter
}
return mask;
}
public static int maxProduct(String[] words) {
int n = words.length;
int[] masks = new int[n];
for (int i = 0; i < n; i++) {
masks[i] = letterMask(words[i]);
}
int best = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((masks[i] & masks[j]) == 0) { // no letter in common
best = Math.max(best, words[i].length() * words[j].length());
}
}
}
return best;
}
public static void main(String[] args) {
for (String w : new String[] {"abcw", "xtfn", "baz"}) {
String bits = Integer.toBinaryString(letterMask(w));
System.out.printf("%-5s %s%n", w, "0".repeat(26 - bits.length()) + bits);
}
String[] example1 = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
System.out.println(maxProduct(example1));
System.out.println(maxProduct(new String[] {"a", "ab", "abc", "d", "cd", "bcd", "abcd"}));
System.out.println(maxProduct(new String[] {"a", "aa", "aaa", "aaaa"}));
System.out.println(maxProduct(new String[] {"aaaa", "bbb"}));
System.out.println(maxProduct(new String[] {"abc"}));
System.out.println(maxProduct(new String[] {}));
}
}
Running it prints:
abcw 00010000000000000000000111
xtfn 00100010000010000000100000
baz 10000000000000000000000011
16
4
0
12
0
0
The three masks match the rows of the picture, with position 0 at the right end. In the line for "abcw", the three 1s on the right are a, b and c, and the 1 fourth from the left is w at position 22. Because Integer.toBinaryStringmain
Next come 16, 4 and 0, the answers to the three examples. The 12 after them comes from ["aaaa", "bbb"]. One mask has only bit 0 set and the other only bit 1, so their AND is 0 and the product is 4 * 3 = 12, however often each letter repeats. The last two lines print 0, because with one word or none there is no pair to test and best
Complexity
The work is reading every letter once to build the masks, plus one AND for every pair of words.
- Time: O(L + n2), because the masks take one read of each of the L letters in all the words, and the two loops then test about n2/2 pairs of n words, one AND each.
- Space: O(n), because the
array holds onemasks for each of the n words, andint copies only one word at a time.toCharArray()