- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Example
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": 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
To Continue Learning Please Login
Login with Google