Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Bit Manipulation

Maximum Product of Word Lengths

Medium · Bit Manipulation · Asked at Google, Amazon, Microsoft

Print the maximum value of length(w1) × length(w2) over all pairs of words that share no common letter, or 0 if no such pair exists.

Input

First line: n. Second line: the n words.

Output

The maximum product.

Constraints

Turn every word into a 26-bit mask of the letters it contains. Two words share no letter exactly when mask1 & mask2 = 0, so each pair is checked in O(1).

Example 1

Input

6
abcw baz foo bar xtfn abcdef

Output

16

Example 2

Input

4
a aa aaa aaaa

Output

0

Hints

  1. Comparing letters of two words directly is slow.
  2. A word’s set of letters fits in 26 bits.
  3. Two words share no letter exactly when the AND of their masks is 0.

Approach

Build mask[i] by setting bit (c − 'a') for every letter of word i. Then check all pairs: if mask[i] & mask[j] == 0, update the best with len[i] · len[j]. Each check is O(1), so the pair loop is O(n²) = 5 × 10^5 for n = 1000.

Complexity: O(total letters + n²) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<string> w(n);
    vector<int> mask(n, 0);
    for (int i = 0; i < n; i++) {
        cin >> w[i];
        for (char c : w[i]) mask[i] |= 1 << (c - 'a');
    }
    long long best = 0;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (!(mask[i] & mask[j])) best = max(best, (long long) w[i].size() * w[j].size());
    cout << best << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
words = data[1 : 1 + n]
masks = []
for w in words:
    m = 0
    for c in set(w):
        m |= 1 << (ord(c) - 97)
    masks.append(m)
lens = [len(w) for w in words]
best = 0
for i in range(n):
    mi, li = masks[i], lens[i]
    for j in range(i + 1, n):
        if not (mi & masks[j]) and li * lens[j] > best:
            best = li * lens[j]
print(best)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] w = br.readLine().trim().split("\\s+");
        int[] mask = new int[n];
        for (int i = 0; i < n; i++)
            for (char c : w[i].toCharArray()) mask[i] |= 1 << (c - 'a');
        long best = 0;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if ((mask[i] & mask[j]) == 0) best = Math.max(best, (long) w[i].length() * w[j].length());
        System.out.println(best);
    }
}

Solve Maximum Product of Word Lengths online · All practice problems