Minimum Deletions to Make String Balanced
Problem Statement
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. The string 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.
Examples
Example 1
- Input:
s = "aababbab" - Output:
2 - Explanation: You can either:
- Delete the characters at 0-indexed positions 2 and 6 (“aababbab” -> “aaabbb”), or
- Delete the characters at 0-indexed positions 3 and 6 (“aababbab” -> “aabbbb”).
Example 2
- Input:
s = "bbaaaaabb" - Output:
2 - Explanation: The only solution is to delete the first two characters.
Constraints
- (1 \leq s.length \leq 10^5)
s[i]is ‘a’ or ‘b’.
Solution
class Solution:
def minimumDeletions(self, s: str) -> int:
n = len(s)
prefix_b = 0 # Count of 'b's up to current position
suffix_a = s.count('a') # Initial count of 'a's from the start to the end
result = suffix_a # Initialize result with the total count of 'a's
for i in range(n):
if s[i] == 'a':
suffix_a -= 1 # Decrease suffix_a as we encounter 'a'
else:
prefix_b += 1 # Increase prefix_b as we encounter 'b'
# Update the minimum deletions needed at each position
result = min(result, prefix_b + suffix_a)
return result
Explanation of the Solution
-
Initialization:
prefix_bstarts at 0 since no 'b’s have been counted yet.suffix_ais initialized to the total count of 'a’s in the string.resultis initialized to the total count of 'a’s because, in the worst case, we might need to delete all 'a’s.
-
Single Iteration:
- Iterate through the string once.
- If the current character is ‘a’, decrement
suffix_asince one ‘a’ is being accounted for as we move from left to right. - If the current character is ‘b’, increment
prefix_b. - At each step, update the
resultwith the minimum of the currentresultand the sum ofprefix_bandsuffix_a.
-
Return Result:
- The
resultwill hold the minimum deletions needed to make the string balanced.
- The
This optimized solution maintains a linear time complexity (O(n)) and requires constant space (O(1)) in addition to the input string.








