Maximum Product of Word Lengths — LeetCode 318 Python Solution
- Problem
- #318
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- words = ["abcw","baz","foo","bar","xtfn","abcdef"]
- Output
- 16
- Explanation
- The two words can be "abcw", "xtfn".
Python solution
class Solution:
def maxProduct(self, words: List[str]) -> int:
mask = [0] * len(words)
ans = 0
for i, s in enumerate(words):
for c in s:
mask[i] |= 1 << (ord(c) - ord("a"))
for j, t in enumerate(words[:i]):
if (mask[i] & mask[j]) == 0:
ans = max(ans, len(s) * len(t))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 + L) |
| Space | O(n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 318. Maximum Product of Word Lengths is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 318. Maximum Product of Word Lengths?
- LeetCode 318. Maximum Product of Word Lengths is rated Medium on LeetCode.
- What is the time complexity of LeetCode 318. Maximum Product of Word Lengths?
- The Python solution on this page runs in O(n^2 + L).
- What is the space complexity of LeetCode 318. Maximum Product of Word Lengths?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 318. Maximum Product of Word Lengths cover?
- LeetCode 318. Maximum Product of Word Lengths is tagged Bit Manipulation, Array and String on LeetCode.