Minimum Deletions to Make String Balanced - Problem
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. A string 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.
Input & Output
Example 1 — Mixed String
$
Input:
s = "aababbab"
›
Output:
2
💡 Note:
Remove the two 'b's at positions 2 and 4 to get "aaaabb" which is balanced: all 'a's come before all 'b's
Example 2 — Already Balanced
$
Input:
s = "bbb"
›
Output:
0
💡 Note:
String contains only 'b's, so it's already balanced (no 'a' comes after 'b')
Example 3 — Reverse Order
$
Input:
s = "baaba"
›
Output:
3
💡 Note:
One optimal solution is to delete 'b', 'a', and 'b' to get "aa" which is balanced
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either 'a' or 'b'
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with mixed 'a' and 'b' characters: "aababbab"
2
Process
Identify positions where 'b' comes before 'a' (imbalance)
3
Output
Minimum deletions needed: 2
Key Takeaway
🎯 Key Insight: A balanced string must have all 'a's before all 'b's - find the optimal split point to minimize deletions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code