Similar Problems

Similar Problems not available

Maximum Deletions On A String - Leetcode Solution

Companies:

LeetCode:  Maximum Deletions On A String Leetcode Solution

Difficulty: Hard

Topics: string dynamic-programming  

Problem statement: Given a string s consisting of only 'A's and 'B's, you can perform the following operation any number of times (possibly zero): Select any contiguous substring of s, and replace it with any string that is the same length and consists only of 'A's and 'B's.

Return the minimum number of operations needed to remove all the 'B's from s.

Example: Input: s = "ABBAB" Output: 2 Explanation: "ABBAB" -> "AxAxA" -> "AAAAA" Where "x" can be either 'A' or 'B'

Solution: To solve this problem, we need to find the number of operations required to remove all the 'B's from the given string. We can start by identifying the substrings of the given string that consist of only 'B's. We can then replace these substrings with a string consisting of 'A's of the same length.

For example, if the given string is “ABBAB”, we can identify two substrings of ‘B’s: “BB” and “B”. We can replace these with ‘A’s: “AA” and “A”. The resultant string is “AAAAA”. This requires two operations.

To identify substrings consisting of only 'B's, we can use a count variable. We can iterate through the string and increment the count variable whenever we encounter a 'B'. If we encounter an 'A', we can reset the count variable to zero. Whenever the count variable reaches a length of greater than zero, we know we have encountered a substring consisting of only 'B's. We can then replace this substring with 'A's and reset the count variable.

Here is the Python code that implements this solution:

def maximumDeletions(s: str) -> int: # count the number of operations operations = 0

# count the number of consecutive Bs
consecutive_bs = 0

# iterate over the string
for i in range(len(s)):
    # if we have a B, increment the count variable
    if s[i] == 'B':
        consecutive_bs += 1
    # if we have an A, replace the consecutive Bs with As
    else:
        if consecutive_bs > 0:
            operations += 1
            consecutive_bs = 0
            
# if we have a substring of Bs at the end of the string, replace it with As
if consecutive_bs > 0:
    operations += 1

return operations

test the function with the example inputs

print(maximumDeletions("ABBAB")) # should return 2

Time Complexity: O(n) Space Complexity: O(1)

Maximum Deletions On A String Solution Code

1