Leetcode 318. Maximum Product of Word Lengths
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.
words
and the maximum length of each word?
words.length
to be up to 10^3
and the length of each word up to 10^3
, but we should confirm.000...0111
).words
where each element contains the bitmask of the word and its length.import java.util.*;
public class Solution {
public int maxProduct(String[] words) {
if (words.length < 2) {
return 0;
}
int n = words.length;
int[] masks = new int[n];
int[] lengths = new int[n];
for (int i = 0; i < n; i++) {
int bitmask = 0;
for (char c : words[i].toCharArray()) {
bitmask |= (1 << (c - 'a'));
}
masks[i] = bitmask;
lengths[i] = words[i].length();
}
int maxProduct = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((masks[i] & masks[j]) == 0) {
maxProduct = Math.max(maxProduct, lengths[i] * lengths[j]);
}
}
}
return maxProduct;
}
}
Thus, the total time complexity is O(N * L + N^2).
This approach ensures that the solution is efficient given usual constraints, but keep in mind that for extremely large inputs, the quadratic part (N^2) might become a bottleneck.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?