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.
1class Solution:
2 def maxProduct(self, words) -> int:
3 n = len(words)
4 masks = [0] * n
5 max_product = 0
6
7 for i, word in enumerate(words):
8 for char in word:
9 masks[i] |= 1 << (ord(char) - ord('a'))
10
11 for i in range(n):
12 for j in range(i + 1, n):
13 if masks[i] & masks[j] == 0:
14 max_product = max(max_product, len(words[i]) * len(words[j]))
15
16 return max_product
17
Each word is represented as a bitmask in a list, where each bit set represents a character present in the word. The solution then evaluates all pairs of words, using bitwise AND to identify if there are any common letters, and calculates and updates the maximum product of their lengths accordingly.
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.