Open In App

Min. length after Deletions of Contiguous “AB” or “CD” Pairs

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string s consisting of only upper case English letters. You can delete contiguous AB or CD from the string any number of times, the task is to return the minimum length of the string after doing possible deletions.

Examples:

Input: “ACBCDAA”
Output: 5
Explanation: The string “ACBCDAA” has one valid deletion “CD.” After deleting these pairs, only “ACBAA” remains, resulting in a minimum length of 5.

Input: “ABCD”
Output: 0
Explanation: In this case, the entire string “ABCD” can be deleted as one contiguous “ABCD” pair, resulting in an empty string with a minimum length of 0.

Input: “ACBABDCCDD”
Output: 4
Explanation: The string “ACBABDCCDD” has three valid deletions, one of “AB” and two of “CD.” After deleting these pairs, “ACBD” remains, resulting in a minimum length of 4.

Approach: To solve the problem follow the below idea:

We can use stack to identify and delete contiguous “AB” or “CD” pairs efficiently. As we traverse the string, we check if the current character can form a valid pair with the character at the top of the stack. If they, we can remove both characters from consideration. Otherwise, we add the character to the stack. This process continues till we reach end of the string.

The remaining characters left in the stack represent those that couldn’t form pairs and thus contribute to the minimum length of the string after deletions.

Follow the steps to solve the problem:

  • Initialize a stack data structure.
  • Iterate through each character in the input string from left to right.
  • For each character Check if the stack is not empty and if the current character can form a valid pair (i.e., “AB” or “CD“) with the character at the top of the stack.
  • If it forms a pair, pop the character from the stack, effectively deleting the pair.
  • If it doesn’t form a pair, push the current character onto the stack.
  • Continue this process until you’ve processed the entire string.
  • After processing, the size of the stack represents the minimum length of the string after all valid deletions.
  • Return the size of the stack as the answer.

Below is the implementation of the above approach:

C++
// C++ code for the above approach:
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;

int minimumLen(string s)
{
    stack<char> stk;
    unordered_map<char, char> mp
        = { { 'A', 'B' }, { 'C', 'D' } };

    for (auto c : s) {

        // Check if the stack is not
        // empty and c matches the
        // corresponding closing character
        if (!stk.empty() && c == mp[stk.top()]) {

            // Delete the pair
            stk.pop();
        }

        // Push the character
        // onto the stack
        else {
            stk.push(c);
        }
    }

    // The stack now contains the
    // minimum number of characters
    // after deletions
    return stk.size();
}

// Drivers code
int main()
{
    string example = "ACBABDCCDD";
    int minLength = minimumLen(example);

    // Function Call
    cout << "Minimum Length after Deletions: " << minLength
        << endl;

    return 0;
}
Java
import java.util.*;

public class Main {
    // Function to find the minimum length after deletions based on specified rules
    static int minimumLength(String s) {
        Stack<Character> stk = new Stack<>();
        HashMap<Character, Character> mp = new HashMap<>();
        mp.put('A', 'B');
        mp.put('C', 'D');

        // Iterate through each character in the input string
        for (char c : s.toCharArray()) {
            // If stack is not empty and the current character matches the pair for the top of the stack
            if (!stk.isEmpty() && c == mp.getOrDefault(stk.peek(), '\0')) {
                // Remove the top character from the stack as it forms a pair with the current character
                stk.pop();
            } else {
                // If no pair is found, push the current character onto the stack
                stk.push(c);
            }
        }

        // Return the remaining length in the stack after deletions
        return stk.size();
    }

    public static void main(String[] args) {
        // Test the function with the example input
        String example = "ACBABDCCDD";
        int minLength = minimumLength(example);

        // Display the minimum length after deletions
        System.out.println("Minimum Length after Deletions: " + minLength);
    }
}
Python3
# Python code for the above approach:
def minimum_len(s):
    stk = []
    mp = {'A': 'B', 'C': 'D'}

    for c in s:
        # Check if the stack is not empty and c matches the corresponding closing character
        if stk and c == mp.get(stk[-1]):
            # Delete the pair
            stk.pop()
        else:
            # Push the character onto the stack
            stk.append(c)

    # The stack now contains the minimum number of characters after deletions
    return len(stk)

# Driver code
if __name__ == "__main__":
    example = "ACBABDCCDD"
    min_length = minimum_len(example)

    # Function Call
    print("Minimum Length after Deletions:", min_length)
 
C#
using System;
using System.Collections.Generic;

public class GFG {
    // Function to find the minimum length after deletions
    // based on specified rules
    static int MinimumLength(string s)
    {
        Stack<char> stk = new Stack<char>();
        Dictionary<char, char> mp
            = new Dictionary<char, char>{ { 'A', 'B' },
                                          { 'C', 'D' } };

        // Iterate through each character in the input
        // string
        foreach(char c in s)
        {
            // If stack is not empty and the current
            // character matches the pair for the top of the
            // stack
            if (stk.Count > 0
                && c
                       == mp.GetValueOrDefault(stk.Peek(),
                                               '\0')) {
                // Remove the top character from the stack
                // as it forms a pair with the current
                // character
                stk.Pop();
            }
            else {
                // If no pair is found, push the current
                // character onto the stack
                stk.Push(c);
            }
        }

        // Return the remaining length in the stack after
        // deletions
        return stk.Count;
    }

    public static void Main(string[] args)
    {
        // Test the function with the example input
        string example = "ACBABDCCDD";
        int minLength = MinimumLength(example);

        // Display the minimum length after deletions
        Console.WriteLine("Minimum Length after Deletions: "
                          + minLength);
    }
}
Javascript
// Js implementation
function minimumLen(s) {
  let stk = [];
  let mp = { A: 'B', C: 'D' };

  for (let c of s) {
    if (stk.length && c === mp[stk[stk.length - 1]]) {
      stk.pop();
    } else {
      stk.push(c);
    }
  }

  return stk.length;
}

const example = 'ACBABDCCDD';
const min_length = minimumLen(example);

console.log('Minimum Length after Deletions:', min_length);

// This code is contributed by Sakshi

Output
Minimum Length after Deletions: 4

Time complexity: O(n), where n is the length of the input string s,
Auxiliary Space: O(1),

Approach: To solve the problem, follow the below idea:

We can also solve the problem using two pointers, i and j where i iterates over the original string S, and j keeps track of the length of the reduced string. For every index i, if S[i] == ‘A’ and S[j – 1] == ‘B’ or if S[i] == ‘C’ and S[j – 1] = ‘D’, then we can remove the last character of the reduced string, therefore reducing the length j to j – 1. Otherwise, we keep on appending the character and increasing the size of the reduced string.

Step-by-step algorithm:

  • Initialize two pointers, i and j, to 0. i is used for iterating through the original string, and j is used for building the resulting string.
  • Iterate through the input string using the while loop until the end of the string is reached.
  • Inside the loop, check for the “AB” and “CD” pairs. If found, decrement the j pointer to skip these characters; otherwise, copy the current character to the resulting string.
  • After the loop, the value of j represents the length of the resulting string after the specified deletions. Return this length.

Below is the implementation of the algorithm:

C++
#include <iostream>

using namespace std;

int minDeletions(string s) {
    int n = s.size();
    int i = 0; // pointer for iterating through the string
    int j = 0; // pointer for building the resulting string

    while (i < n) {
        if (j > 0 && s[i] == 'B' && s[j - 1] == 'A') {
            // Found "AB" pair, skip these characters
            j--;
        } else if (j > 0 && s[i] == 'D' && s[j - 1] == 'C') {
            // Found "CD" pair, skip these characters
            j--;
        } else {
            // No valid pair, copy the character to the resulting string
            s[j++] = s[i];
        }

        i++;
    }

    return j;
}

int main() {
    // Example 1
    string s1 = "ACBCDAA";
    cout << "Minimum length: " << minDeletions(s1) << endl;

    // Example 2
    string s2 = "ABCD";
    cout << "Minimum length: " << minDeletions(s2) << endl;
    
    string s3 = "ACBABDCCDD";
    cout << "Minimum length: " << minDeletions(s3) << endl;

    return 0;
}
Java
// Java program for the above approach
import java.util.*;

public class GFG {
    public static int minDeletions(String s)
    {
        int n = s.length();
        int i
            = 0; // pointer for iterating through the string
        int j = 0; // pointer for building the resulting
                   // string
        char[] chars
            = s.toCharArray(); // Convert string to char
                               // array for mutable
                               // manipulation

        while (i < n) {
            if (j > 0 && chars[i] == 'B'
                && chars[j - 1] == 'A') {
                // Found "AB" pair, skip these characters
                j--;
            }
            else if (j > 0 && chars[i] == 'D'
                     && chars[j - 1] == 'C') {
                // Found "CD" pair, skip these characters
                j--;
            }
            else {
                // No valid pair, copy the character to the
                // resulting string
                chars[j++] = chars[i];
            }

            i++;
        }

        return j;
    }

    public static void main(String[] args)
    {
        // Example 1
        String s1 = "ACBCDAA";
        System.out.println("Minimum length: "
                           + minDeletions(s1));

        // Example 2
        String s2 = "ABCD";
        System.out.println("Minimum length: "
                           + minDeletions(s2));

        // Example 3
        String s3 = "ACBABDCCDD";
        System.out.println("Minimum length: "
                           + minDeletions(s3));
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Python function to find the minimum length of resulting string after removing "AB" and "CD" pairs

def minDeletions(s):
    n = len(s)
    i = 0  # pointer for iterating through the string
    j = 0  # pointer for building the resulting string
    chars = list(s)  # Convert string to list for mutable manipulation

    while i < n:
        if j > 0 and chars[i] == 'B' and chars[j - 1] == 'A':
            # Found "AB" pair, skip these characters
            j -= 1
        elif j > 0 and chars[i] == 'D' and chars[j - 1] == 'C':
            # Found "CD" pair, skip these characters
            j -= 1
        else:
            # No valid pair, copy the character to the resulting string
            chars[j] = chars[i]
            j += 1

        i += 1

    return j

# Example usage:
# Example 1
s1 = "ACBCDAA"
print("Minimum length:", minDeletions(s1))

# Example 2
s2 = "ABCD"
print("Minimum length:", minDeletions(s2))

# Example 3
s3 = "ACBABDCCDD"
print("Minimum length:", minDeletions(s3))
JavaScript
function minDeletions(s) {
    let n = s.length;
    let i = 0; // Pointer for iterating through the string
    let j = 0; // Pointer for building the resulting string

    while (i < n) {
        if (j > 0 && s[i] === 'B' && s[j - 1] === 'A') {
            // Found "AB" pair, skip these characters
            j--;
        } else if (j > 0 && s[i] === 'D' && s[j - 1] === 'C') {
            // Found "CD" pair, skip these characters
            j--;
        } else {
            // No valid pair, copy the character to the resulting string
            s = s.substr(0, j) + s[i] + s.substr(j + 1);
            j++;
        }

        i++;
    }

    return j;
}

// Example usage
let s1 = "ACBCDAA";
console.log("Minimum length:", minDeletions(s1));

let s2 = "ABCD";
console.log("Minimum length:", minDeletions(s2));

let s3 = "ACBABDCCDD";
console.log("Minimum length:", minDeletions(s3));

Output
Minimum length: 5
Minimum length: 0
Minimum length: 4

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads