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
Minimum Deletions to Make String Balanced INPUT String s = "aababbab" a 0 a 1 b 2 a 3 b 4 b 5 a 6 b 7 Balanced: all 'a's before all 'b's No 'b' before 'a' pattern allowed Bad Patterns Found: s[2]='b' before s[3]='a' s[4]='b' before s[6]='a' s[5]='b' before s[6]='a' Input Values s = "aababbab" Length: 8 characters ALGORITHM STEPS Single Pass - Running Balance 1 Initialize counters bCount=0, deletions=0 2 Scan left to right Track 'b' count as we go 3 For each character If 'b': bCount++ If 'a' and bCount>0: deletions++, bCount-- 4 Return deletions Min deletions needed Execution Trace: idx chr bCnt del 0,1 a,a 0 0 2 b 1 0 3 a 0 1 4,5 b,b 2 1 6 a 1 2 7 b 2 2 FINAL RESULT Characters to delete marked: a a b a b b a b Balanced String: a a b b b "aabbb" - All a's before b's Output 2 OK - Verified! Deleted 2 'a's at indices 3,6 Result is balanced: "aabbb" Key Insight: When we encounter an 'a' after seeing 'b's, we have a conflict. Instead of actually deciding which to delete, we track "virtual deletions". Each deletion reduces both the problem size and b-count, giving O(n) time complexity. The algorithm greedily resolves 'ba' conflicts. TutorialsPoint - Minimum Deletions to Make String Balanced | Single Pass Running Balance Approach
Asked in
Facebook 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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