- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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": 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))

"sststtst"

2

- Related Questions & Answers
- Program to find minimum number of deletions required from two ends to make list balanced in Python
- Program to find minimum deletions to make strings strings in Python
- Program to count minimum deletions needed to make character frequencies unique in Python
- Minimum number of deletions to make a string palindrome in C++.
- Program to find minimum number of operations to make string sorted in Python
- Finding minimum deletions in string in JavaScript
- Program to find minimum moves to make array complementary in Python
- Program to find minimum operations to make array equal using Python
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum remove required to make valid parentheses in Python
- Program to find minimum operations to make the array increasing using Python
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum one bit operations to make integers zero in Python
- Program to find minimum number of days to wait to make profit in python
- Program to check minimum number of characters needed to make string palindrome in Python

Advertisements