forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_111.js
61 lines (49 loc) Β· 1.51 KB
/
problem_111.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
52
53
54
55
56
57
58
59
60
61
/**
* Find all starting anagram indicies
* @param {string} word
* @param {string} string
* @return {number[]}
*/
function findAnagrams(word, string) {
const indicies = [];
if (string.length > word.length) return indicies;
// build a frequence count for string
const freqCount = new Map();
for (let i = 0; i < string.length; i++) {
const char = string.charAt(i);
if (freqCount.has(char)) {
freqCount.set(char, freqCount.get(char) + 1);
} else {
freqCount.set(char, 1);
}
}
let counter = string.length;
let start = 0;
let end = 0;
while (end < word.length) {
const endChar = word.charAt(end);
if (freqCount.has(endChar)) {
// we decrement, and can have negative count
if (freqCount.get(endChar) >= 1) counter--;
freqCount.set(endChar, freqCount.get(endChar) - 1);
}
while (counter === 0) {
const startChar = word.charAt(start);
// two seperate conditions
// 1. for incrementing counter for extending the window size
// 2. Since our counter is 0 and the window length is the correct length, push the start index
if (freqCount.has(startChar)) {
freqCount.set(startChar, freqCount.get(startChar) + 1);
// when the start count for character is positive, we can break out our loop
if (freqCount.get(startChar) > 0) counter++;
}
// check window size
if (end - start + 1 === string.length) {
indicies.push(start);
}
start++;
}
end++;
}
return indicies;
}