Maximum Product of Word Lengths
Master this topic with zero to advance depth.
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
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
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.
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
Detailed Dry Run
"abcw" -> mask = 0x400007 "xtfn" -> mask = 0x882020 mask1 & mask2 = 0. Product = 4 * 4 = 16.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.