#318
Maximum Product of Word Lengths
MediumArrayStringBit ManipulationBit ManipulationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses bit manipulation to represent each word as a bitmask. This allows us to quickly check for common letters using bitwise operations, significantly reducing the time complexity.
⚙️
Algorithm
4 steps- 1Step 1: Create an array to store the bitmask for each word, where each bit represents a letter in the alphabet.
- 2Step 2: For each word, compute its bitmask and store it in the array.
- 3Step 3: Use two nested loops to compare the bitmasks of each pair of words. If the bitwise AND of the two masks is 0, they share no common letters.
- 4Step 4: Calculate the product of their lengths and update the maximum product accordingly.
solution.py20 lines
1# Full working Python code
2words = ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
3
4def maxProduct(words):
5 n = len(words)
6 masks = [0] * n
7 lengths = [0] * n
8 for i in range(n):
9 for char in words[i]:
10 masks[i] |= (1 << (ord(char) - ord('a')))
11 lengths[i] = len(words[i])
12
13 max_product = 0
14 for i in range(n):
15 for j in range(i + 1, n):
16 if masks[i] & masks[j] == 0:
17 max_product = max(max_product, lengths[i] * lengths[j])
18 return max_product
19
20print(maxProduct(words))ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but the bit manipulation allows us to check for common letters in constant time. The space complexity is O(n) for storing the masks and lengths.
- 1Using bit manipulation can significantly speed up the process of checking for common letters.
- 2Understanding how to represent characters as bits can lead to more efficient solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.