Problem Link

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 <= 105
  • s[i] isΒ 'a' or 'b'​​.

Solution


C++

class Solution {
public:
    int minimumDeletions(string s) {
        int N = s.size(), res = N;
        vector<int> prefixB(N + 1, 0), suffixA(N + 1, 0);
 
        for (int i = 0; i < N; i++) {
            prefixB[i + 1] = prefixB[i] + (s[i] == 'b');
        }
 
        for (int i = N - 1; i >= 0; i--) {
            suffixA[i] = suffixA[i + 1] + (s[i] == 'a');
        }
 
        for (int i = 0; i <= N; i++) {
            res = min(res, prefixB[i] + suffixA[i]);
        }
 
        return res;
    }
};

Python3

class Solution:
    def minimumDeletions(self, s: str) -> int:
        c = collections.Counter(s)
        
        a_right = c["a"]
        b_right = c["b"]
        
        a_left = b_left = 0
        res = len(s)
        
        for c in s+"b":
 
            res = min(res, b_left + a_right)
                
            if c == "a":
                a_left += 1
                a_right -= 1
            else:
                b_left += 1
                b_right -= 1
            
            
        
        return res