
You are given, ‘str’ = ‘aabba’, and ‘K’ = 2, The longest substring with each character’s frequency at least ‘K’ is ‘aabba’, whose length is 5. Hence the answer is 5.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘K’ representing the integer given.
The second line of each test case contains the string ‘str’ representing the given string.
For each test case print a single integer representing the longest substring with the frequency of each character at least K.
Print a separate line for each test case.
1 <= T <= 10
1 <= K <= 10^5
1 <= |str| <= 10^4
Time Limit: 1 sec
In this approach, we can traverse over every substring of the given string and check if all of its characters have a minimum frequency of ‘K’.
If a substring has all characters with a minimum frequency of ‘K’ we try to update our solution with its length.
We will create an isStringValid(subStr, k) method, that checks if the ‘subStr’ has all characters with a minimum frequency of k.
Algorithm:
In this approach, we will use the sliding window approach to find the window of the biggest length.
For Example, if we have string = ‘aabbb…’ and K = 3, what should we do when we reach the window ’aabbb’.
One way to handle this problem is to do several sliding window passes, where we fix diffChars, the number of different symbols we must have in our substring. So, we check all possible diffChars = 1, ... 26 (if fact, not 26, but the number of unique characters in the string) and do a sliding window pass.
In this approach, we will count the frequencies of all characters in the string. We know that any character which has a frequency less than K, won't be part of a valid substring so if we find a character with less than K frequency, we can divide the string on either side of that character and recursively call our function.