Problem Description
Given a string s consisting only of characters 'a' and 'b', determine the minimum number of deletions needed to make s balanced. A string is balanced if there is no pair of indices (i, j) where i < j with s[i] = 'b' and s[j] = 'a'. Essentially, all 'a's should appear before any 'b's in the final string.
Key Insights
- A balanced string means every 'a' must come before every 'b'.
- When scanning the string, conflicts occur when an 'a' appears after a 'b'.
- At each 'a', we face a choice: delete the current 'a' or delete all preceding 'b's.
- By maintaining a counter for 'b's and tracking the minimum deletions required so far, we can decide optimally at each step.
- This approach leverages a greedy/dynamic programming method with a single pass.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string. Space Complexity: O(1) since only a few variables are used.
Solution
The solution iterates through the string while keeping track of two variables: countB (the number of 'b's encountered so far) and deletionCount (the minimum deletions required up to the current point). For each character:
- If the character is 'b', increment countB.
- If the character is 'a', update deletionCount to be the minimum of either deleting this 'a' (deletionCount + 1) or deleting all previous 'b's (which is countB). This strategy ensures that the final deletionCount reflects the minimum number of deletions needed to achieve a balanced string.