Skip to content
Problem 318 · LeetCode 318(opens in a new tab)

Maximum Product of Word Lengths

MediumBit manipulation

You are given a list of lowercase words, words. Pick two of them 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:  words = ["bad", "cafe", "hop", "joking"]
Output: 24
Why:    "cafe" and "joking" share no letter: 4 × 6
2 more examples and the constraints

Example 2

Input:  words = ["aa", "aaa", "a"]
Output: 0
Why:    every pair shares the letter a

Example 3

Input:  words = ["xy", "z", "xyz", "w"]
Output: 3
Why:    "xyz" and "w" share nothing: 3 × 1

Constraints

  • 2 ≤ number of words ≤ 1,000
  • 1 ≤ length of each word ≤ 1,000
  • Words use only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare letters per pairO(n² · L)
  2. Letter bit masksO(n² + total letters)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 words of 1,000 lettersVerdict
Compare letters per pairO(n² · L)
Re-reads words for every pair
Letter bit masksO(n² + total letters)
Best; one AND per pair

n = number of words, L = length of the longest word.

Edge cases to test

  • No valid pair. ["aa", "aaa", "a"]: every pair shares a, so the answer is 0.
  • Repeated letters. "eeeeee" has mask {e} but length 6; use the real length in the product.
  • A word with every letter. It shares a letter with every other word, so it never counts.
  • Duplicate words. ["moon", "moon", "sun"]: the two copies overlap with each other; moon × sun = 12.

Common mistakes

  • Writing masks[i] & masks[j] == 0 without parentheses in Java, C++ or TypeScript, where == binds tighter than &.
  • Using the number of distinct letters instead of the word length in the product.
  • Pairing a word with itself (j starting at i instead of i + 1).

How to talk through it

  1. 1Clarify. Only lowercase letters? Return 0 if no pair works? Do repeated letters count in the length?
  2. 2Give the brute force. Every pair, compare letters: O(n² · L), letters re-read for each pair.
  3. 3Shrink each word. Only the set of letters matters, and 26 letters fit in one int.
  4. 4Code the masks. Build masks in one pass; then an AND of 0 means no shared letter.
  5. 5Test out loud. Run the all-a case for 0 and a word with repeated letters.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?