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 Lengths INPUT words array: "abcw" "baz" "foo" "bar" "xtfn" "abcdef" Bitmask Encoding "abcw" --> 0...00010111 "baz" --> 0...00000111 "foo" --> 0...01100000 "bar" --> 0...00000111 "xtfn" --> 0...10110100000 "abcdef"--> 0...00111111 Each bit represents a letter (a=bit0, b=bit1...) 6 words to process ALGORITHM STEPS 1 Create Bitmasks For each word, set bit for each character 2 Compare Pairs Check all word pairs using AND operation 3 Check No Common If mask1 AND mask2 = 0 No shared letters! 4 Track Maximum Update max product len(w1) * len(w2) Example: "foo" AND "xtfn" 01100000 10110100 00000000 = 0 [OK] FINAL RESULT Best pair found: "abcw" len = 4 x "xtfn" len = 4 No common letters: {a,b,c,w} ∩ {x,t,f,n} = {} Product Calculation: 4 x 4 = 16 Output: 16 [OK] Maximum found! Checked 15 word pairs Key Insight: Character Set Optimization Using bitmasks to represent character sets allows O(1) comparison of two words. If (mask1 AND mask2) equals 0, the words share no common letters. This reduces complexity from O(n*m) per pair to O(1), making total time O(n^2) for n words. TutorialsPoint - Maximum Product of Word Lengths | Character Set Optimization Approach
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