Maximum Product of Word Lengths (LeetCode 318): Solution and Explanation

Medium
Array
String
Bit Manipulation

Given a list of lowercase words, find two words that have no letter in common and return the largest product of their lengths. If every pair shares a letter, return 0.

Intuition

The answer has to look at pairs, because a pair is only valid when the two words are letter-disjoint. With up to 1000 words there are about half a million pairs, which is fine. What is not fine is spending O(L) time per pair scanning strings that can each be 1000 letters long.

Notice that the shared-letter question only depends on which letters each word contains, not how many times or in what order. There are only 26 lowercase letters, so that set fits in the low 26 bits of an integer: bit k is on when letter 'a' + k appears.

Once each word is a mask, two words share a letter exactly when their masks have a common 1 bit, which is the same as mask_i & mask_j != 0. The pair check drops to a single AND, and the rest is a plain double loop that keeps the best product.

Approach: Letter bitmasks plus all pairs

  1. Create masks, one integer per word, all starting at 0.
  2. For each word and each letter ch in it, set masks[i] |= 1 << (ch - 'a').
  3. Set best = 0.
  4. For every pair i < j, if masks[i] & masks[j] == 0 the words share no letter, so update best with len(words[i]) * len(words[j]).
  5. Return best.

Step-by-step example

words = ["abcw","baz","foo","bar","xtfn","abcdef"]
  1. Masks: abcw = {a,b,c,w}, baz = {a,b,z}, foo = {f,o}, bar = {a,b,r}, xtfn = {f,n,t,x}, abcdef = {a,b,c,d,e,f}.
  2. Pair (0,1) abcw and baz: the AND keeps a and b, so skip. Pair (0,2) abcw and foo: AND is 0, product 4 * 3 = 12, best = 12.
  3. Pair (0,4) abcw and xtfn: AND is 0, product 4 * 4 = 16, best = 16.
  4. Pair (1,2) baz and foo gives 9 and pair (2,3) foo and bar gives 9, both smaller than 16. Pair (2,4) foo and xtfn share f.
  5. Pair (3,4) bar and xtfn gives 12, and every pair with abcdef shares a letter. The answer is 16.

Code: Python, Java, C++

1class Solution:
2    def maxProduct(self, words: List[str]) -> int:
3        n = len(words)
4        masks = [0] * n
5        for i, w in enumerate(words):
6            for ch in w:
7                masks[i] |= 1 << (ord(ch) - ord('a'))
8        best = 0
9        for i in range(n):
10            for j in range(i + 1, n):
11                if masks[i] & masks[j] == 0:
12                    best = max(best, len(words[i]) * len(words[j]))
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(L + n^2)

Building the masks touches every letter once, L letters in total. The pair loop runs n(n-1)/2 times with O(1) work per pair.

Space

O(n)

One integer mask per word.

Other approaches

Compare letter sets directly (time O(L + 26 n^2), space O(n))

For each pair, build or reuse a set of letters and test for intersection. It is correct but each check costs up to 26 operations plus hashing overhead, so it is several times slower than one AND.

Keep the longest word per mask (time O(L + m^2) for m distinct masks, space O(m))

Many words can share the same letter set. Store only the longest length for each distinct mask in a hash map, then loop over pairs of distinct masks. This helps when there are many duplicates and gives the same answer.

Common mistakes

  • Writing masks[i] & masks[j] == 0 in Java, C++ or C# without parentheses. == binds tighter than &, so wrap the AND first.
  • Using ^ or | instead of &. Only AND detects a letter both words contain.
  • Forgetting that the answer is 0 when no pair is disjoint. Starting best at 0 handles it.

Frequently asked questions

Why does a 32-bit int suffice for the mask?

There are only 26 lowercase letters, so the highest bit used is bit 25. A 32-bit integer has room to spare.

Do repeated letters matter?

No. OR-ing the same bit twice leaves it on, so "foo" and "fo" have the same mask. The length still comes from the original word.

Can the product overflow?

No. Each length is at most 1000, so the product is at most 1,000,000, well inside a 32-bit int.

Is there something faster than checking every pair?

Not in the worst case for this problem, but deduplicating masks and keeping the longest word per mask shrinks the pair loop when many words share a letter set.