Minimum Deletions to Make String Balanced

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, s[i] = 'b', and s[j] = 'a'.

Return the minimum number of deletions needed to make s balanced.

Example 1
Inputs = "aababbab"
Output2
You can delete the characters at 0-indexed positions 2 and 6 to get "aaabbb", or delete the characters at positions 3 and 6 to get "aabbbb".
Example 2
Inputs = "bbaaaaabb"
Output2
The only solution is to delete the first two characters.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is 'a' or 'b'.

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate