Program to find minimum deletions to make string balanced in Python

Suppose we have a string s with only two characters 's' and 't'. We can delete any number of characters of s to make the string balanced. We can say, s is balanced when there is no pair of indices (i,j) such that i < j and s[i] = 't' and s[j]= 's'. We have to find the minimum number of deletions needed to make s balanced.

So, if the input is like s = "sststtst", then the output will be 2 because we can either, remove the characters at indices 2 and 6 ("sststtst" to "sssttt"), or remove the characters at indices 3 and 6 ("sststtst" to "sstttt").

To solve this, we will follow these steps −

  • cum_b := 0

  • count_a := number of character 's' in s

  • ans := infinity

  • for each x in s, do

    • if x is same as "s", then

      • count_a := count_a - 1

      • ans := minimum of ans and (cum_b + count_a)

    • otherwise,

      • cum_b := cum_b + 1

      • ans := minimum of ans and (cum_b-1 + count_a)

  • return ans


Let us see the following implementation to get better understanding −

def solve(s):
   cum_b = 0
   count_a = s.count("s")
   ans = float("inf")
   for x in s:
      if x == "s":
         ans = min(ans,cum_b + count_a)
         ans = min(ans,cum_b-1 + count_a)
   return ans

s = "sststtst"