


If the given string S = “abcbaacd” and k = 2. In the first operation, we will remove ‘aa’ from the string. After that, we will concatenate the left and right strings as the resultant string will be “abcb” + “cd” = “abcbcd”.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ denoting the number of characters present in string S and ‘K’.
The following line contains the string ‘S’.
For each test case, print ‘an integer corresponding to the minimum number of swaps required.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^4.
1 <= K <= 1000.
Time limit: 1 sec
In this approach, we will simply check the string and if we found any substring having ‘K’ adjacent equal characters, we will remove that substring and make a recursive call for the new resultant string.
In this approach, we will first define an array of ‘C’ for size ‘N’.C[i] will store the number of the same adjacent characters till S[i]. Now, we will declare two pointers i and j.j will denote the ending index of our final resultant string and we will iterate i to check the frequency and calculate the value of C[i].wIf we found C[i] == ‘K’, we will delete that substring and update our j pointer.
At last the final resultant string will be the substring of S from index 0 to j-1.
In this approach, we will build up a stack that will store two things character and frequency of that adjacent repetition of that character. We will simply iterate over the string and count the frequency of that adjacent repetition. Whenever we found a frequency of ‘K’ , we will pop that element from the stack and discard that substring from our final answer.
At last, we will form our resultant string using the elements of the stack.