304 North Cardinal St.
Dorchester Center, MA 02124

Maximum Product of Word Lengths LeetCode Solution

Problem – Maximum Product of Word Lengths LeetCode Solution

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`.

Example 1:

``````Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
``````

Example 2:

``````Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
``````

Example 3:

``````Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
``````

Constraints:

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

Maximum Product of Word Lengths LeetCode Solution in Java

``````	public static int maxProduct(String[] words) {
if (words == null || words.length == 0)
return 0;
int len = words.length;
int[] value = new int[len];
for (int i = 0; i < len; i++) {
String tmp = words[i];
value[i] = 0;
for (int j = 0; j < tmp.length(); j++) {
value[i] |= 1 << (tmp.charAt(j) - 'a');
}
}
int maxProduct = 0;
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++) {
if ((value[i] & value[j]) == 0 && (words[i].length() * words[j].length() > maxProduct))
maxProduct = words[i].length() * words[j].length();
}
return maxProduct;
}
``````

Maximum Product of Word Lengths LeetCode Solution in C++

``````int maxProduct(vector<string>& words) {
int result = 0;
for (int i=0; i<words.size(); ++i) {
for (char c : words[i])
mask[i] |= 1 << (c - 'a');
for (int j=0; j<i; ++j)
result = max(result, int(words[i].size() * words[j].size()));
}
return result;
}
``````

Maximum Product of Word Lengths LeetCode Solution in Python

``````class Solution(object):
def maxProduct(self, words):
d = {}
for w in words:
for c in set(w):
mask |= (1 << (ord(c) - 97))
return max([d[x] * d[y] for x in d for y in d if not x & y] or [0])
``````
Maximum Product of Word Lengths LeetCode Solution Review:

In our experience, we suggest you solve this Maximum Product of Word Lengths LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Maximum Product of Word Lengths LeetCode Solution

Find on Leetcode

Conclusion:

I hope this Maximum Product of Word Lengths LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions