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
String Balancing: "baaba" ExampleOriginal StringbaabaIndex: 01234Step-by-step Processing1Process 'b': b_count = 1, deletions = 02Process 'a': Conflict! Delete 'a', b_count = 0, deletions = 13Process 'a': No conflict, keep it4Process 'b': b_count = 1, deletions = 15Process 'a': Conflict! Delete 'a', b_count = 0, deletions = 2Algorithm Stateb_count: tracks 'b's seendeletions: running totalWhen 'a' found:โ€ข If b_count > 0: conflict!โ€ข Delete 'a', decrement b_countโ€ข Else: keep 'a', no changeResult: 2 deletions needed
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.
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
42.2K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen