LeetCode Entry
1653. Minimum Deletions to Make String Balanced
Min removal to balance 'ab'
1653. Minimum Deletions to Make String Balanced medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1261
Problem TLDR
Min removal to balance ‘ab’ #medium #greedy
Intuition
Split at each position and compare left and right counts of ‘a’ and ‘b’. The greedy intuition: count ‘b’, at each ‘a’ choose min of (remove ‘a’=d+1, keep ‘a’=b count removed)
Approach
- the corner cases of single ‘a’ and ‘b’ should be checked
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 24ms
fun minimumDeletions(s: String): Int {
var b = 0
return min(0,s.minOf { b += 2*(it - 'a')-1; b }) + s.count{it=='a'}
}
// 10ms
pub fn minimum_deletions(s: String) -> i32 {
s.bytes().fold((0,0),|(b,d),c|if c>b'a'{(b+1,d)}else{(b,b.min(d+1))}).1
}