-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (42 loc) · 1.37 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @param {string[]} words1
* @param {string[]} words2
* @return {string[]}
*/
// frequency map 1
// https://leetcode.com/problems/word-subsets/discuss/1128227/JavaScript-Combine-Words-in-B-into-One
/**********************************************************************************************
* Runtime: 301 ms, faster than 62.62% of JavaScript online submissions for Word Subsets. *
* Memory Usage: 67.5 MB, less than 51.64% of JavaScript online submissions for Word Subsets. *
**********************************************************************************************/
var wordSubsets = function(words1, words2) {
const output = [];
const freqB = Array(26).fill(0);
for (let wordB of words2) {
const currFreq = getFreq(wordB);
for (let i = 0; i < freqB.length; i++) {
freqB[i] = Math.max(freqB[i], currFreq[i]);
}
}
for (let wordA of words1) {
const freqA = getFreq(wordA);
const universal = isSubset(freqA);
if (universal) output.push(wordA);
}
function isSubset(freqA) {
for (let i = 0; i < freqA.length; i++) {
if (freqB[i] > freqA[i]) return false;
}
return true;
}
function getFreq(word) {
const map = Array(26).fill(0);
for (let char of word) {
const idx = char.charCodeAt() - 'a'.charCodeAt();
map[idx]++;
}
return map;
}
return output;
};
export default wordSubsets;