

- 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
Program to find minimum number of characters to be deleted to make A's before B's in Python
Suppose we have a string s consisting only two letters A and B, we have to find the minimum number of letters that need to be deleted from s to get all occurrences of As before all occurrences of Bs.
So, if the input is like S = "AABAABB", then the output will be 1, as We can remove the last A to get AABBB
To solve this, we will follow these steps:
a_right := number of occurrences of "A" in s
b_left := 0
ans := a_right
for each index i and character c in s, do
if c is same as "A", then
a_right := a_right - 1
otherwise,
b_left := b_left + 1
ans := minimum of ans and a_right + b_left
return ans
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, s): a_right = s.count("A") b_left = 0 ans = a_right for i, c in enumerate(s): if c == "A": a_right -= 1 else: b_left += 1 ans = min(ans, a_right + b_left) return ans ob = Solution() S = "AABAABB" print(ob.solve(S))
Input
"AABAABB"
Output
1
- Related Questions & Answers
- Program to find minimum number of characters to be added to make it palindrome in Python
- Program to find minimum digits sum of deleted digits in Python
- Program to check minimum number of characters needed to make string palindrome in Python
- Program to find minimum number of operations to make string sorted in Python
- Program to find minimum number of days to wait to make profit in python
- Find minimum number to be divided to make a number a perfect square in C++
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum number of days to make m bouquets using Python
- Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python
- Python program to find Maximum and minimum element’s position in a list?
- Program to find minimum number of heights to be increased to reach destination in Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Program to count number of distinct substrings in s in Python
- Print digit’s position to be removed to make a number divisible by 6 in C++
- Program to find minimum number of operations required to make one string substring of other in Python
Advertisements