Maximum Product of Word Lengths

Medium

Topics
ArrayStringBit Manipulation

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

abcwbazfoobarxtfnabcdef
Input:  words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: "abcw" and "xtfn" share no letters: 4 * 4 = 16.

Example 2

aaaaaaaaaa
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

  1. Build a bitmask per word: set bit c - 'a' for each letter.
  2. For every pair (i, j), if mask[i] & mask[j] == 0 they are disjoint.
  3. 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 & mask is the mask itself, which is non-zero for any non-empty word, so the pair is rejected by the overlap test anyway. The i + 1 start 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 res
SensAI
Beta
Tap the mic to stop voice mode