Skip to content

1653. Minimum Deletions to Make String Balanced 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  // Same as 926. Flip String to Monotone Increasing
  int minimumDeletions(string s) {
    // the number of characters to be deleted to make the substring so far
    // balanced
    int dp = 0;
    int countB = 0;

    for (const char c : s)
      if (c == 'a')
        // 1. Delete 'a'.
        // 2. Keep 'a' and delete the previous 'b's.
        dp = min(dp + 1, countB);
      else
        ++countB;

    return dp;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  // Same as 926. Flip String to Monotone Increasing
  public int minimumDeletions(String s) {
    // the number of characters to be deleted to make subString so far balanced
    int dp = 0;
    int countB = 0;

    for (final char c : s.toCharArray())
      if (c == 'a')
        // 1. Delete 'a'.
        // 2. Keep 'a' and delete the previous 'b's.
        dp = Math.min(dp + 1, countB);
      else
        ++countB;

    return dp;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  # Same as 926. Flip String to Monotone Increasing
  def minimumDeletions(self, s: str) -> int:
    dp = 0  # the number of characters to be deleted to make subso far balanced
    countB = 0

    for c in s:
      if c == 'a':
        # 1. Delete 'a'.
        # 2. Keep 'a' and delete the previous 'b's.
        dp = min(dp + 1, countB)
      else:
        countB += 1

    return dp