Sponsored
Sponsored
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.
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.
1var maxProduct = function(words) {
2 const n = words.length;
3 const masks = new Array(n).fill(0);
4 let maxProduct = 0;
5
6 for (let i = 0; i < n; i++) {
7 for (const char of words[i]) {
8 masks[i] |= 1 << (char.charCodeAt(0) - 'a'.charCodeAt(0));
9 }
10 }
11
12 for (let i = 0; i < n; i++) {
13 for (let j = i + 1; j < n; j++) {
14 if ((masks[i] & masks[j]) === 0) {
15 maxProduct = Math.max(maxProduct, words[i].length * words[j].length);
16 }
17 }
18 }
19
20 return maxProduct;
21};
22
This JavaScript solution creates a bitmask for each word representing the presence of each letter. It then compares each pair of words using bitwise operations to check if they have common letters, and computes the maximum product of their lengths when they have no common letters.
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.
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.
1class Solution:
2 def maxProduct(self
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.