Skip to content

Latest commit

 

History

History
67 lines (51 loc) · 2.69 KB

README.md

File metadata and controls

67 lines (51 loc) · 2.69 KB

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

Companies:
Microsoft, Swiggy

Related Topics:
String, Dynamic Programming, Stack

Similar Questions:

Solution 1. Left-to-Right State Transition

Scan s and try using each point as a breakpoint. Keep track of the number of as to the left and number of bs to the right. For each breackpoint, the longest string we can form is of length a + b. We find the global maximum of such length, and the answer is N minus this maximum value.

// OJ: https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int minimumDeletions(string s) {
        int a = 0, b = 0, N = s.size();
        for (char c : s) b += c == 'b';
        int ans = b;
        for (int i = 0; i < N; ++i) {
            a += s[i] == 'a';
            b -= s[i] == 'b';
            ans = max(ans, a + b);
        }
        return N - ans;
    }
};