Maximum Product of Word Lengths LeetCode solution in JavaScript

1
/**
2
* @param {string[]} words
3
* @return {number}
4
*/
5
var maxProduct = function (words) {
6
words.sort((a, b) => b.length - a.length);
7

8
const m = new Map();
9
for (let word of words) {
10
if (m.has(word)) continue;
11
const alpha = new Array(26).fill(0);
12
for (let w of word) {
13
let idx = w.charCodeAt(0) - "a".charCodeAt(0);
14
alpha[idx] = 1;
15
}
16
m.set(word, parseInt(alpha.join(""), 2));
17
}
18

19
const hasCommonLetters = (a, b) => {
20
const sb = m.get(b);
21
const sa = m.get(a);
22
return (sa & sb) != 0;
23
};
24
let ans = 0,
25
len = words.length;
26
for (let i = 0; i < len; i++) {
27
for (let j = i + 1; j < len; j++) {
28
if (!hasCommonLetters(words[i], words[j])) {
29
ans = Math.max(ans, words[i].length * words[j].length);
30
}
31
}
32
}
33
return ans;
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0