
Consider the string 'Str' = “aabbbab”, you can delete character ‘a’ at the 5th index to make the string balanced ("aabbbab" -> "aabbbb"). Hence, the answer is 1.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows.
The first line of each test case contains a string ‘Str’ representing the given string.
For each test case, print a single integer representing the minimum number of deletions needed to make ‘Str’ balanced.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1<= T <= 10
1 <= |Str| <= 10^6
Str[i] contains only characters 'a' and 'b'.
Time limit: 1 sec
Let’s take a decision on the current character of the string and let recursion do the rest of the work. We will create a helper function to do the task.
The approach will be the same as what we did in the recursive brute force approach. But this time, we will count the number of ‘a’ ahead for each index ‘i’ before calling recursion.
Let’s solve this problem backward. Instead of deleting characters from the string, let’s think about the possible strings that we can make, for example, whatever string ‘S’ has been given to us, we know that we ultimately want it in the form of “aaa...bbb...bb”
So using this idea, let’s take an initial String ‘T’ = “bbb...bb”, and check the minimum number of operations required to make the current string ‘Str’ = ‘T’.
After that, we will iterate at each character and try to convert our string ‘T’ to
And so on.
So at each iteration, we can easily calculate the operations required to make string ‘S’ = ‘T”, minimum of all the operations is going to be our answer.
Algorithm: