/**
* Problem: LeetCode 1653 - Minimum Deletions to Make String Balanced
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int minimumDeletions(String s) {
int bCount = 0;
int deletions = 0;
for (char c : s.toCharArray()) {
if (c == 'b') {
bCount++;
} else {
// For character 'a', we either delete this 'a' (deletions + 1)
// or keep it by deleting all prior 'b' characters (bCount).
deletions = Math.min(deletions + 1, bCount);
}
}
return deletions;
}
}
"""
Problem: LeetCode 1653 - Minimum Deletions to Make String Balanced
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def minimumDeletions(self, s: str) -> int:
b_count = 0
deletions = 0
for ch in s:
if ch == 'b':
b_count += 1
else:
# Either delete this 'a' or delete all previous 'b's
deletions = min(deletions + 1, b_count)
return deletions
/**
* Problem: LeetCode 1653 - Minimum Deletions to Make String Balanced
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int minimumDeletions(string s) {
int bCount = 0;
int deletions = 0;
for (char c : s) {
if (c == 'b') {
bCount++;
} else {
// Either delete this 'a' or delete all previous 'b's
deletions = min(deletions + 1, bCount);
}
}
return deletions;
}
};
/**
* Problem: LeetCode 1653 - Minimum Deletions to Make String Balanced
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} s
* @return {number}
*/
var minimumDeletions = function(s) {
let bCount = 0;
let deletions = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === 'b') {
bCount++;
} else {
// Either delete this 'a' or delete all previous 'b's
deletions = Math.min(deletions + 1, bCount);
}
}
return deletions;
};
TIME COMPLEXITY
O(n)
SPACE COMPLEXITY
O(1)
TOPICS
Dynamic Programming
Greedy
Prefix Sum
Stack
String