Maximum Product of Word Lengths — LeetCode 318 Python Solution

MediumBit ManipulationArrayString
Problem
#318
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n^2 + L)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview