Min. length after Deletions of Contiguous "AB" or "CD" Pairs
Last Updated :
10 Apr, 2024
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
OutputMinimum 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));
OutputMinimum length: 5
Minimum length: 0
Minimum length: 4
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem