You are given a string ‘Str’ consisting of only characters ‘a’ and ‘b’. You can delete any number of characters in ‘Str’ to make ‘Str’ balanced.
A string is called balanced if there is no pair of indices (i, j) such that i < j, Str[i] = ’b’ and Str[j] = ’a’. You have to return the minimum number of deletions to make the ‘Str’ balanced.
For example: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.
Output Format :
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.
Note :
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
2
aabbbab
aabbbb
1
0
For test case 1 :
You can delete character ‘a’ at the 5th index to make the string balanced ("aabbbab" -> "aabbbb"). Hence, the answer is 1.
For test case 2 :
The given string is already balanced, so no operations are needed. Hence the answer is 0.
2
bbaaabb
aaaabba
2
1
Try to think of an approach by using recursion.
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.
Algorithm:
O(N^2), where ‘N’ is the length of String ‘Str’.
At each index, we are also calculating the number of ‘a’ ahead, we are doing N^2 operations. Hence the overall time complexity will be O(N^2).
O(N), where ‘N’ is the length of String ‘Str’.
The recursion stack requires O(N) space. Hence, the overall space complexity is O(N).