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 <= 10001 <= words[i].length <= 1000words[i] consists only of lowercase English letters.This approach uses bit manipulation to represent each word with a bitmask where each bit corresponds to a character ('a' to 'z'). This allows comparison of character sets in constant time using a bitwise AND operation. If two words have no common characters, their corresponding bitmask AND result should be zero.
The solution first computes a bitmask for each word using each character's position in the alphabet. Then, it iterates through all possible pairs of words, checking if their bitmasks overlap. If they do not overlap, it means the words do not share common letters, and it calculates their length product, updating the maximum product accordingly.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N^2 + L), where N is the number of words and L is the total number of characters across all words.
Space Complexity: O(N), as we require an array to store bit masks for each word.
This approach involves iterating through each pair of words, using a set to represent the characters of each word. For each pair, it checks if there are any common letters using set intersection. This method is straightforward but less efficient than bit manipulation for larger input sizes.
In this Python solution, each word is converted into a set of characters. The method then goes through each pair of words and checks for common letters using set intersection. If no common letters exist—and thereby the intersection is an empty set—it calculates their length product and updates the maximum product.
Java
Time Complexity: O(N^2 * L) where L is the average length of the words.
Space Complexity: O(N * L) as each word is stored in a set.
| Approach | Complexity |
|---|---|
| Bitmask for Character Representation | Time Complexity: O(N^2 + L), where N is the number of words and L is the total number of characters across all words. |
| Nested Loop with Set Comparison | Time Complexity: O(N^2 * L) where L is the average length of the words. |
Maximum Product Subarray - Dynamic Programming - Leetcode 152 • NeetCode • 452,934 views views
Watch 9 more video solutions →Practice Maximum Product of Word Lengths with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor