Maximum Product of Word Lengths
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Maximum Product of Word Lengths
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.Examples
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Approach 1
Level I: Brute Force (Check All Pairs)
Intuition
Iterate through every pair of words and check if they have common characters using a helper function.
Thought Process
- Nested loop for all pairs.
- For each pair:
- Check overlap: For char in word[i], is it in word[j]?
- If no overlap, update
maxProd.
Pattern: Double Iteration
⏱ O(N^2 \cdot L) - Where $N$ is number of words and $L$ is max word length.💾 O(1) - Assuming constant alphabet space.
Approach 2
Level II: Precomputed Sets
Intuition
For each word, precompute a set of its characters. When comparing two words, check if their character sets have any intersection. This is faster than a raw character-by-character check but slower than bitmasking.
⏱ $O(N^2 + N \cdot L)$💾 $O(N \cdot 26)$
Approach 3
Level III: Optimal (Bitmasking)
Intuition
Each word can be represented by a 26-bit integer (bitmask). Two words share NO common letters if and only if their bitwise AND is 0.
Thought Process
- Precompute bitmasks for all words.
- Nested loop and check
(masks[i] & masks[j]) == 0. - Update max product.
Pattern: Alphabet Bitmasking
⏱ O(N^2 + N \cdot L) - $O(N \cdot L)$ to build masks, $O(N^2)$ to compare pairs.💾 O(N) - To store the bitmasks.
Detailed Dry Run
"abcw" -> mask = 0x400007
"xtfn" -> mask = 0x882020
mask1 & mask2 = 0. Product = 4 * 4 = 16.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.