# Program to find minimum number of characters to be deleted to make A's before B's in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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