Find Common Characters LeetCode solution in JavaScript

1
var commonChars = function (words) {
2
//record the first word characters in an array called minFreq
3
//iterater over the rest of the input array
4
//record the characters for each word called freq
5
//update the corresponding minFreq element to the smaller one between each word and the first word
6
//after collect all the words' freq and update the minFreq, iterate over the minReq
7
//push the element to the result
8
let res = [],
9
minFreq = new Array(26).fill(0);
10
let firstWord = words[0];
11
for (let i = 0; i < firstWord.length; i++) {
12
let index = firstWord.charCodeAt(i) - 97;
13
minFreq[index]++;
14
}
15
for (let word of words) {
16
let freq = new Array(26).fill(0);
17
for (let i = 0; i < word.length; i++) {
18
let index = word.charCodeAt(i) - 97;
19
freq[index]++;
20
}
21
for (let i = 0; i < 26; i++) {
22
minFreq[i] = Math.min(minFreq[i], freq[i]);
23
}
24
}
25
for (let i = 0; i < 26; i++) {
26
for (let q = 0; q < minFreq[i]; q++) {
27
let letter = String.fromCharCode(i + 97);
28
res.push(letter);
29
}
30
}
31
return res;
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0