Problem Description
You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced.
Key Insights
- A string is balanced if all 'a's appear before any 'b's.
- The problem can be reduced to counting how many deletions are required to achieve this order.
- We can maintain a count of 'a's and 'b's while iterating through the string to determine the minimum deletions needed.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
To solve this problem, we can use a single pass through the string while maintaining two counters: one for the total number of 'a's and another for the deletions needed. As we encounter 'b's in the string, we can calculate how many 'a's need to be deleted to keep the string balanced. The algorithm works as follows:
- Initialize counters for total 'a's and deletions.
- Traverse the string character by character.
- For each 'a', increase the total count of 'a's.
- For each 'b', increase the deletion count by the number of 'a's encountered so far.
- At the end of the traversal, the deletion count will represent the minimum deletions required.