Minimum Deletions to Make String Balanced - Problem
You are given a string s consisting only of characters 'a' and 'b'. Your task is to make the string balanced by deleting the minimum number of characters.
A string is considered balanced if there is no pair of indices (i, j) such that i < j, s[i] = 'b', and s[j] = 'a'. In other words, all 'a' characters must appear before all 'b' characters.
Goal: Return the minimum number of deletions needed to make the string balanced.
Example: In string "baaba", we have 'b' at index 0 followed by 'a' at indices 1, 2, and 4, making it unbalanced. We need to delete 2 characters to get "aab" which is balanced.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aababbab"
โบ
Output:
2
๐ก Note:
We can delete the first 'b' and last 'b' to get "aaabab" โ "aaaaab". Actually, we delete 2 characters to make it "aababa" โ "aaaba" (remove one 'b' in middle and last 'b').
example_2.py โ Simple Case
$
Input:
s = "baba"
โบ
Output:
2
๐ก Note:
We can delete the 'b' at index 0 and 'a' at index 3, leaving "aa". Or delete both 'a's leaving "bb". Both need 2 deletions.
example_3.py โ Already Balanced
$
Input:
s = "aaabbb"
โบ
Output:
0
๐ก Note:
The string is already balanced (all 'a's come before all 'b's), so no deletions are needed.
Constraints
- 1 โค s.length โค 105
- s[i] is either 'a' or 'b'
- The string contains only lowercase characters 'a' and 'b'
Visualization
Tap to expand
Understanding the Visualization
1
Scan Left to Right
Process each character while maintaining balance
2
Count B's
Keep track of how many 'b's we've seen
3
Resolve Conflicts
When we see 'a' after 'b', delete optimally
4
Update Counters
Maintain running count of deletions and conflicts
Key Takeaway
๐ฏ Key Insight: At each 'a', we face a choice: delete this 'a' or delete previous 'b's. The optimal strategy is to always resolve conflicts immediately by deleting the 'a', which gives us O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code