Minimum Deletions to Make String Balanced

medium dynamic programming string prefix

Problem

You are given a string s of only 'a' and 'b'. The string is balanced when there is no pair of indices i < j with s[i] = 'b' and s[j] = 'a' — i.e. every 'b' comes after every 'a'. Return the minimum number of characters you must delete to make s balanced.

Inputs = "aababbab"
Output2
Delete positions 2 and 6 to get "aaabbb" — two deletions suffice.
Inputs = "bbaaaaabb"
Output2
Delete the two leading b's so all remaining a's precede all b's.

def min_deletions(s):
    res = 0       # min deletions so far
    b_count = 0   # number of 'b' seen so far
    for ch in s:
        if ch == 'b':
            b_count += 1
        else:
            # delete this 'a', or delete all earlier 'b's
            res = min(res + 1, b_count)
    return res
function minDeletions(s) {
  let res = 0;      // min deletions so far
  let bCount = 0;   // number of 'b' seen so far
  for (const ch of s) {
    if (ch === 'b') {
      bCount++;
    } else {
      // delete this 'a', or delete all earlier 'b's
      res = Math.min(res + 1, bCount);
    }
  }
  return res;
}
int minDeletions(String s) {
    int res = 0;       // min deletions so far
    int bCount = 0;    // number of 'b' seen so far
    for (char ch : s.toCharArray()) {
        if (ch == 'b') {
            bCount++;
        } else {
            // delete this 'a', or delete all earlier 'b's
            res = Math.min(res + 1, bCount);
        }
    }
    return res;
}
int minDeletions(string s) {
    int res = 0;       // min deletions so far
    int bCount = 0;    // number of 'b' seen so far
    for (char ch : s) {
        if (ch == 'b') {
            bCount++;
        } else {
            // delete this 'a', or delete all earlier 'b's
            res = min(res + 1, bCount);
        }
    }
    return res;
}
Time: O(n) Space: O(1)