Maximum Number of Occurrences of a Substring LeetCode solution in JavaScript

1
var maxFreq = function (s, maxLetters, minSize, maxSize) {
2
let output = 0;
3

4
let left = 0,
5
right = 0;
6

7
let map = {};
8

9
let map2 = {};
10

11
let count = 0;
12

13
while (right < s.length) {
14
if (map[s[right]] === undefined) {
15
// adding letters to map to keep track of occurences (count)
16
map[s[right]] = 1;
17
count++;
18
} else {
19
if (map[s[right]] === 0) {
20
count++;
21
}
22
map[s[right]]++;
23
}
24

25
if (right - left + 1 > minSize) {
26
// once over minSize removing occurence of left most letter from map and adjusting count
27

28
map[s[left]]--;
29
if (map[s[left]] < 1) {
30
count--;
31
}
32
left++;
33
}
34

35
if (right - left + 1 >= minSize && count <= maxLetters) {
36
map2[s.substring(left, right + 1)] =
37
(map2[s.substring(left, right + 1)] || 0) + 1; // if subsitrng meets constraints of size and count add to map2;
38
}
39

40
right++;
41
}
42

43
Object.entries(map2).map(([key, val]) => (output = Math.max(output, val))); // get largest value in map2
44

45
return output;
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0