-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1002-find-common-characters.js
More file actions
58 lines (51 loc) · 1.7 KB
/
1002-find-common-characters.js
File metadata and controls
58 lines (51 loc) · 1.7 KB
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
52
53
54
55
56
57
58
/**
* Find Common Characters
* Time Complexity: O(N * L)
* Space Complexity: O(L)
*/
var commonChars = function (words) {
const alphabetSizeConstant = 26;
const asciiOffsetForA = "a".charCodeAt(0);
const minCharacterCounts = new Array(alphabetSizeConstant).fill(0);
const initialWord = words[0];
for (const charOfInitialWord of initialWord) {
const indexInAlphabet = charOfInitialWord.charCodeAt(0) - asciiOffsetForA;
minCharacterCounts[indexInAlphabet]++;
}
for (let wordIndex = 1; wordIndex < words.length; wordIndex++) {
const currentWordString = words[wordIndex];
const currentWordCharacterCounts = new Array(alphabetSizeConstant).fill(0);
for (const charOfCurrentWordString of currentWordString) {
const currentAlphabetIndex =
charOfCurrentWordString.charCodeAt(0) - asciiOffsetForA;
currentWordCharacterCounts[currentAlphabetIndex]++;
}
for (
let comparisonIterator = 0;
comparisonIterator < alphabetSizeConstant;
comparisonIterator++
) {
minCharacterCounts[comparisonIterator] = Math.min(
minCharacterCounts[comparisonIterator],
currentWordCharacterCounts[comparisonIterator],
);
}
}
const finalResultList = [];
for (
let charIteratorForResult = 0;
charIteratorForResult < alphabetSizeConstant;
charIteratorForResult++
) {
const charCountForElement = minCharacterCounts[charIteratorForResult];
const charToAdd = String.fromCharCode(
asciiOffsetForA + charIteratorForResult,
);
let appendLoopCounter = 0;
while (appendLoopCounter < charCountForElement) {
finalResultList.push(charToAdd);
appendLoopCounter++;
}
}
return finalResultList;
};