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
Input: ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Output: 16
Explanation: "abcw" and "xtfn" share no letters: 4 * 4 = 16.
Example 2
Input: ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Output: 4
Explanation: "ab" and "cd" share no letters: 2 * 2 = 4.
Example 3
Input: ["a", "aa", "aaa", "aaaa"]
Output: 0
Explanation: every pair shares the letter 'a'.
Solution

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 int, which has 32 bits, numbered from position 0 on the right to 31 on the left. Letter 'a' gets bit position 0, 'b' gets position 1, and so on up to 'z' at position 25. An int whose bits record the letters of one word is called a bitmask of that word, or mask for short. Look at the picture below.

The masks of abcw, xtfn and baz, one bit per letter, with position 0 for a on the right and 25 for z on the left. abcw AND xtfn is 0, so they share no letter. abcw AND baz has bits 0 and 1 set, for a and b.

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, &, lines the two numbers up and keeps a 1 only in the positions where both have a 1. The 1s of "abcw" and "xtfn" sit in different columns, so "abcw" AND "xtfn" is 0.

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 char is a number, so c - 'a' gives the letter's position: 0 for 'a', 1 for 'b', and 25 for 'z'. Then 1 << (c - 'a') shifts a single 1 that many places to the left, giving a number with only that bit set. For 'w' that is 1 << 22.

The bitwise OR operator, |, adds that bit to the mask: mask |= 1 << (c - 'a') turns the letter's bit on and leaves the others as they are. A repeated letter, like the second 'o' in "foo", turns on a bit that is already on, so the mask does not change.

Could a mask turn out negative? Java stores an int in 32 bits using two's complement, where a 1 in bit 31 means the number is negative. The letters only reach bit 25, so bits 26 to 31 stay 0 and every mask is a positive number.

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 keeps the largest candidate so far.

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> from mask to the longest length with that mask can replace the list, and Example 3 then has one entry instead of four words. When all the masks differ, as in Example 1, this saves nothing.

Java Solution

The method maxProduct works in these steps:

  1. First, a helper method, letterMask, builds the mask of one word. It starts mask at 0 and, for each character c of the word, turns on its bit with mask |= 1 << (c - 'a').
  2. In maxProduct, a first loop fills an array masks with one int per word, so masks[i] is the mask of words[i].
  3. A variable best starts at 0. Two loops, one inside the other, visit every pair: the outer loop moves i over all the words, and the inner loop moves j over the words after position i.
  4. When masks[i] & masks[j] is 0, the two words share no letter, and best becomes the larger of itself and words[i].length() * words[j].length().
  5. After the last pair, the method returns best, which is still 0 if no pair passed the test.

The main method prints the masks of "abcw", "xtfn" and "baz" as 26 binary digits, then runs the three examples, two words made of one repeated letter each, a list with one word, and an empty list.

Java
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:

Output
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.toBinaryString leaves out leading zeros, main pads each mask back to 26 digits.

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 keeps its starting value.

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 masks array holds one int for each of the n words, and toCharArray() copies only one word at a time.