1653. 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. 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'​​.

Intuition

Take count of all Those before B's and All after a's for all index

Now the addition for each index tells me the deletion I want to do 
To eliminiate the inversions

https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/description/?envType=daily-question&envId=2024-07-30

Approach 1:

C++
class Solution {
public:
    int minimumDeletions(string s) {
        int n = s.size();
        vector<int> b(n, 0);

        for(int i=1; i<n; i++){
            if(s[i-1] == 'b'){
                b[i] = b[i-1] + 1;
            }else{
                b[i] = b[i-1];
            }
        }


        int ans = INT_MAX;
        for(int i=0; i<n; i++){
            ans = min(ans, a[i]+b[i]);
        }

        return ans;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated