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.
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 <= s.length <= 105s[i]is'a'or'b'.
Approach 01:
-
C++
-
Python
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int minimumDeletions(string s) {
int minDeletions = 0; // Minimum deletions to make the string balanced
int countB = 0; // Count of 'b's encountered so far
for (const char c : s) {
if (c == 'a') {
// Either delete this 'a' or keep it and delete some 'b's seen before
minDeletions = min(minDeletions + 1, countB);
} else {
++countB; // Increment count of 'b's
}
}
return minDeletions;
}
};
class Solution:
def minimumDeletions(self, s: str) -> int:
minDeletions = 0 # Minimum deletions to make the string balanced
countB = 0 # Count of 'b's encountered so far
for c in s:
if c == 'a':
# Either delete this 'a' or keep it and delete some 'b's seen before
minDeletions = min(minDeletions + 1, countB)
else:
countB += 1 # Increment count of 'b's
return minDeletions
Time Complexity
- Initialization:
Initializing
minDeletionsandcountBtakes \( O(1) \) time. - Traversal of String:
We traverse the string
sonce, which takes \( O(n) \) time, where \( n \) is the length of the string. - Operations within Loop:
Inside the loop, the operations (checking characters and updating variables) are all \( O(1) \) operations.
- Overall Time Complexity:
The overall time complexity is \( O(n) \).
Space Complexity
- Space for Variables:
The space used by the variables
minDeletionsandcountBis \( O(1) \). - Input String:
The input string
sis provided as input, so it does not count towards the space complexity. - Overall Space Complexity:
The overall space complexity is \( O(1) \).