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

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

"AABAABB"

1

- Related Questions & Answers
- Program to find number of string we can make where 'a' can be 'a' or 'b', and 'b' remains 'b'in Python
- 8085 program to find 1's and 2's complement of 8-bit number
- 8085 program to find 1's and 2's complement of 16-bit number
- Program to find minimum number of characters to be added to make it palindrome in Python
- How to delete all children's elements using Python's Tkinter?
- Program to generate Pascal's triangle in Python
- Python program using map function to find row with maximum number of 1's
- Minimum Swaps to Group All 1's Together in Python
- Program to find the nth row of Pascal's Triangle in Python
- How to find only Monday's date with Python?
- What's the Kotlin equivalent of Java's String[]?
- 1's Complement vs 2's Complement
- How to make any Django model's file downloadable?
- Python program using the map function to find a row with the maximum number of 1's
- Program to find out an MST using Prim's algorithm in Python

Advertisements