Leetcode 318: Maximum Product of Word Lengths

grid47
grid47
Exploring patterns and algorithms
Oct 6, 2024 5 min read

A set of words with glowing lengths, each word’s length highlighted to show the maximum product of word lengths.
Solution to LeetCode 318: Maximum Product of Word Lengths Problem

Given a list of words, return the maximum product of lengths of two words such that the two words do not share common letters. If no such pair exists, return 0.
Problem
Approach
Steps
Complexity
Input: The input is a list of words, where each word consists of lowercase English letters.
Example: words = ["abc", "xyz", "foo", "bar", "pqr", "abcdef"]
Constraints:
• 2 <= words.length <= 1000
• 1 <= words[i].length <= 1000
• words[i] consists of lowercase English letters
Output: Return the maximum product of lengths of two words that do not share common letters.
Example: 15
Constraints:
• If no such pair exists, return 0.
Goal: To find the maximum product of lengths of two words where the words do not share any common letters.
Steps:
• For each word, calculate its bitmask where each bit represents whether a letter is present in the word.
• For each pair of words, check if the bitmasks do not overlap (i.e., they share no common letters).
• Calculate the product of the lengths of words that do not share any common letters, and track the maximum product.
Goal: The solution should handle a large number of words and word lengths efficiently.
Steps:
• Ensure that the solution works efficiently for strings up to 1000 characters and up to 1000 words.
Assumptions:
• The words are non-empty and consist of lowercase English letters.
Input: words = ["abc", "xyz", "foo", "bar", "pqr", "abcdef"]
Explanation: The two words with no common letters are 'abc' and 'xyz'. The product of their lengths is 15, which is the maximum.

Input: words = ["a", "ab", "ac", "b", "bc"]
Explanation: The maximum product is 2, obtained by the words 'a' and 'bc'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus