MediumNo. 0318

Maximum Product of Word Lengths — LeetCode 318 Python Solution

Topics
Bit Manipulation, Array, String
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

PythonSolution
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

Time
O(n2 + L)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0067Add BinaryEasy
0136Single NumberEasy
0137Single Number IIMedium
0260Single Number IIIMedium
0287Find the Duplicate NumberMedium
0393UTF-8 ValidationMedium

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(n2 + 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.

Free to download. Check it runs on your machine, then pick a plan.