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.
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'.
Solutions
This function also uses a counter-based approach similar to the previous solution, but with cleaner syntax using a for...of loop instead of indexed iteration. It counts the 'b' characters encountered and for each 'a' that has preceding 'b' characters (checked via b > 0), it increments the result and decrements the counter, essentially matching each 'a' with a preceding 'b' to determine the minimum deletions needed.
Language: javascript(2026-02-07 10:29)DONE
CPU Performance66.67%
Memory Performance36.36%
/**
* @param {string} s
* @return {number}
*/
var minimumDeletions = function(s) {
let b = 0;
let res = 0;
for (const char of s) {
if (char === 'b') {
b++;
} else if (b > 0) {
b--;
res++;
}
}
return res;
};