Maximum Product of Word Lengths

Given a string array `words`, return the largest value of `length(words[i]) * length(words[j])` over pairs of words that share no letter. If no such pair exists, return 0.

30:00

Maximum Product of Word Lengths
medium
Free written solution
Topics
Companies

Given a string array words, return the largest value of length(words[i]) * length(words[j]) over pairs of words that share no letter. If no such pair exists, return 0.

Example 1:
Input: {"words":["abcw","baz","foo","bar","xtfn","abcdef"]}
Output: 16
Constraints:
  • 2≤words.length≤10002 \leq \text{words.length} \leq 1000

  • 1≤words[i].length≤10001 \leq \text{words[i].length} \leq 1000

  • words[i] consists only of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["abcw","baz","foo","bar","xtfn","abcdef"]}

6 words. Comparing letters pair by pair is slow, so first squeeze each word into a 26-bit mask: bit k is on when letter 'a' + k appears.

words (index, word, length)

0

abcw

4

1

baz

3

2

foo

3

3

bar

3

4

xtfn

4

5

abcdef

6

26 slots, one per letter a..z

pairs checked 0/15

best = 0
Variables
VariableValue
n6
DepthFunction Call
Stack empty
0/29