Leetcode 318. Maximum Product of Word Lengths
You are given an array of strings words
. Each word consists of lowercase English letters.
Your task is to find the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters.
words
array, and what is the maximum length of an individual word?
0
.1
) or not (0
).#include <vector>
#include <string>
#include <algorithm>
int maxProduct(std::vector<std::string>& words) {
int n = words.size();
if (n == 0) return 0;
// Step 1: Convert words to bitmasks
std::vector<int> bitmasks(n, 0);
for (size_t i = 0; i < n; ++i) {
for (char c : words[i]) {
bitmasks[i] |= 1 << (c - 'a');
}
}
// Step 2: Find max product of lengths of pairs of different words without common letters
int max_prod = 0;
for (size_t i = 0; i < n; ++i) {
for (size_t j = i + 1; j < n; ++j) {
if ((bitmasks[i] & bitmasks[j]) == 0) {
int prod = words[i].length() * words[j].length();
max_prod = std::max(max_prod, prod);
}
}
}
return max_prod;
}
L
is the average length of a word. Hence, O(N * L) for all words.Therefore, the overall time complexity is O(N^2 + N * L), which simplifies to O(N^2) for pairs comparison in practice, as L is relatively small compared to N.
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?