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

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

Example

Let us see the following implementation to get better understanding −

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

Input

"sststtst"

Output

2
Updated on: 2021-10-06T07:28:25+05:30

552 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements