Maximum Product of Word Lengths - Problem

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.

If no such two words exist, return 0.

Input & Output

Example 1 — Basic Case
$ Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
💡 Note: The two words can be "abcw" and "xtfn". "abcw" has letters {a,b,c,w} and "xtfn" has letters {x,t,f,n}. No common letters, so product = 4 × 4 = 16.
Example 2 — No Valid Pairs
$ Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
💡 Note: The two words can be "ab" and "cd". "ab" has letters {a,b} and "cd" has letters {c,d}. No overlap, product = 2 × 2 = 4.
Example 3 — All Words Share Letters
$ Input: words = ["a","aa","aaa","aaaa"]
Output: 0
💡 Note: All words contain the letter 'a', so no two words can be chosen without sharing common letters.

Constraints

  • 2 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 1000
  • words[i] consists only of lowercase English letters.

Visualization

Tap to expand
Maximum Product of Word LengthsFind two words with no common letters to maximize length productabcwbazfoobarxtfnabcdeflen=4len=3len=3len=3len=4len=6"abcw"+"xtfn"{a,b,c,w}{x,t,f,n}No common letters! ✓Product = 4 × 4 = 16Maximum Product: 16
Understanding the Visualization
1
Input
Array of words: ["abcw","baz","foo","bar","xtfn","abcdef"]
2
Process
Find pairs with no common letters, calculate length products
3
Output
Maximum product: "abcw" × "xtfn" = 4 × 4 = 16
Key Takeaway
🎯 Key Insight: Use bitmasks to convert O(m×n) character comparison to O(1) bitwise AND operation
Asked in
Google 45 Facebook 38 Microsoft 32 Amazon 28
78.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen