
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Program to find minimum number of characters to be added to make it palindrome in Python
- Program to check minimum number of characters needed to make string palindrome in Python
- Program to find minimum digits sum of deleted digits 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
- Program to find minimum number of operations required to make one number to another in Python
- Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python
- Program to find minimum number of days to make m bouquets using Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Find minimum number to be divided to make a number a perfect square in C++
- 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 one string substring of other in Python
- Program to find minimum number of bricks required to make k towers of same height in Python
- Program to find minimum moves to make array complementary in Python
- Program to find minimum deletions to make string balanced in Python

Advertisements