Longest Substring with At Least K Repeating Characters LeetCode solution in JavaScript

1
var longestSubstring = function (s, k) {
2
let n = s.length;
3
if (n == 0 || n < k) return 0;
4
if (k == 1) return n;
5

6
const freq = {}; // object to store the freq of each character ex . { 'a' : 2 , 'b' : 1 ...}
7

8
// counting the freq. of each character
9
for (let i = 0; i < n; i++) {
10
let char = s[i];
11
if (freq[char])
12
// if the character is already present , increase it's freq.
13
freq[char]++;
14
else freq[char] = 1; // else assign the freq. as 1
15
}
16
let i = 0;
17
while (i < n && freq[s[i]] >= k)
18
// while loop continue till the freq. of character is greater than or equal to k
19
i++;
20

21
if (i >= n - 1)
22
// if i == string.length
23
return i;
24

25
let left1 = longestSubstring(s.substring(0, i), k); // dividing the string at index where freq. of character is less than k and calling the func again on the substring
26

27
while (i < n && freq[s[i]] < k)
28
// ignore the char whose freq. is less than k
29
i++;
30

31
let right1 = longestSubstring(s.substring(i), k); // second part of the string
32

33
return Math.max(left1, right1);
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0