KatInterview

318. Maximum Product of Word Lengths

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Bitmasking

The core of this problem is to efficiently check if two words share any common letters. A naive approach of iterating through all characters for every pair of words would be too slow, leading to a time complexity of roughly O(N² * L²), where N is the number of words and L is the average length. We need a faster way to perform this check.

Solution

Maximum Product of Word Lengths in Python

class Solution:
    def maxProduct(self, words: List[str]) -> int:
        n = len(words)
        if n < 2:
            return 0

        # Create a list to store the bitmask for each word.
        # Each bit from 0 to 25 corresponds to a letter 'a' through 'z'.
        masks = [0] * n
        for i in range(n):
            for char in words[i]:
                # Set the bit corresponding to the character.
                masks[i] |= (1 << (ord(char) - ord('a')))
        
        max_prod = 0
        # Iterate through all unique pairs of words.
        for i in range(n):
            for j in range(i + 1, n):
                # If the bitwise AND of two masks is 0, they have no common characters.
                if (masks[i] & masks[j]) == 0:
                    # Calculate the product of lengths and update the maximum.
                    max_prod = max(max_prod, len(words[i]) * len(words[j]))
        
        return max_prod

Maximum Product of Word Lengths in Java

class Solution {
    public int maxProduct(String[] words) {
        int n = words.length;
        if (n < 2) {
            return 0;
        }

        // Create an array to store the bitmask for each word.
        // Each bit from 0 to 25 corresponds to a letter 'a' through 'z'.
        int[] masks = new int[n];
        for (int i = 0; i < n; i++) {
            for (char c : words[i].toCharArray()) {
                masks[i] |= (1 << (c - 'a'));
            }
        }

        int maxProd = 0;
        // Iterate through all unique pairs of words.
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // If the bitwise AND of two masks is 0, they have no common characters.
                if ((masks[i] & masks[j]) == 0) {
                    // Calculate the product of lengths and update the maximum.
                    maxProd = Math.max(maxProd, words[i].length() * words[j].length());
                }
            }
        }

        return maxProd;
    }
}

Maximum Product of Word Lengths in C++

class Solution {
public:
    int maxProduct(vector<string>& words) {
        int n = words.size();
        if (n < 2) {
            return 0;
        }

        // Create a vector to store the bitmask for each word.
        // Each bit from 0 to 25 corresponds to a letter 'a' through 'z'.
        vector<int> masks(n, 0);
        for (int i = 0; i < n; ++i) {
            for (char c : words[i]) {
                masks[i] |= (1 << (c - 'a'));
            }
        }

        int max_prod = 0;
        // Iterate through all unique pairs of words.
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                // If the bitwise AND of two masks is 0, they have no common characters.
                if ((masks[i] & masks[j]) == 0) {
                    // Calculate the product of lengths and update the maximum.
                    // Using static_cast to avoid potential overflow with size_t, though not strictly necessary with problem constraints.
                    max_prod = max(max_prod, static_cast<int>(words[i].length() * words[j].length()));
                }
            }
        }

        return max_prod;
    }
};

Maximum Product of Word Lengths in TypeScript

function maxProduct(words: string[]): number {
    const n = words.length;
    if (n < 2) {
        return 0;
    }

    // Create an array to store the bitmask for each word.
    // Each bit from 0 to 25 corresponds to a letter 'a' through 'z'.
    const masks = new Array(n).fill(0);
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < words[i].length; j++) {
            const charCode = words[i].charCodeAt(j) - 'a'.charCodeAt(0);
            masks[i] |= (1 << charCode);
        }
    }

    let maxProd = 0;
    // Iterate through all unique pairs of words.
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            // If the bitwise AND of two masks is 0, they have no common characters.
            if ((masks[i] & masks[j]) === 0) {
                // Calculate the product of lengths and update the maximum.
                maxProd = Math.max(maxProd, words[i].length * words[j].length);
            }
        }
    }

    return maxProd;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.