Reduce the string to minimum length with the given operation

Given a string str consisting of lowercase and uppercase characters, the task is to find the minimum possible length the string can be reduced to after performing the given operation any number of times. In a single operation, any two consecutive characters can be removed if they represent the same character in different cases i.e. “aA” and “Cc” can be removed but “cc” and “EE” cannot be removed.

Examples:

Input: str = “ASbBsd”
Output: 2
Operations 1: “ASbBsd” -> “ASsd”
Operations 2: “ASsd” -> “Ad”
The string cannot be reduced further.



Input: str = “AsSaDda”
Output: 1
Operations 1: “AsSaDda” -> “AaDda”
Operations 2: “AaDda” -> “Dda”
Operations 3: “Dda” -> “a”

Approach:

  • Create a stack to store the characters of the string.
  • For every character of the string starting from the first character, if the stack is empty then push the current character in the stack.
  • Else match the current character with the top of the stack, if they only differ in the case then pop the element from the stack and continue.
  • If they are not equal then push the current element to the stack and repeat the above steps for the rest of the string.
  • The size of the stack in the end is the required answer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the minimum
// possible length str can be reduced
// to with the given operation
int minLength(string str, int len)
{
  
    // Stack to store the characters
    // of the given string
    stack<char> s;
  
    // For every character of the string
    for (int i = 0; i < len; i++) {
  
        // If the stack is empty then push the
        // current character in the stack
        if (s.empty()) {
            s.push(str[i]);
        }
        else {
  
            // Get the top character
            char c = s.top();
  
            // If the top element is not equal
            // to the current element and it
            // only differs in the case
            if (c != str[i]
                && toupper(c) == toupper(str[i])) {
  
                // Pop the top element from stack
                s.pop();
            }
  
            // Else push the current element
            else {
                s.push(str[i]);
            }
        }
    }
  
    return s.size();
}
  
// Driver code
int main()
{
    string str = "ASbBsd";
    int len = str.length();
  
    cout << minLength(str, len);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG 
{
  
// Function to return the minimum
// possible length str can be reduced
// to with the given operation
static int minLength(String str, int len)
{
  
    // Stack to store the characters
    // of the given string
    Stack<Character> s = new Stack<Character>();
  
    // For every character of the string
    for (int i = 0; i < len; i++) 
    {
  
        // If the stack is empty then push the
        // current character in the stack
        if (s.empty()) 
        {
            s.push(str.charAt(i));
        }
        else
        {
  
            // Get the top character
            char c = s.peek();
  
            // If the top element is not equal
            // to the current element and it
            // only differs in the case
            if (c != str.charAt(i) && 
                Character.toUpperCase(c) == 
                Character.toUpperCase((str.charAt(i)))) 
            {
  
                // Pop the top element from stack
                s.pop();
            }
  
            // Else push the current element
            else 
            {
                s.push(str.charAt(i));
            }
        }
    }
    return s.size();
}
  
// Driver code
public static void main(String []args) 
{
    String str = "ASbBsd";
    int len = str.length();
  
    System.out.println(minLength(str, len));
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# Function to return the minimum 
# possible length str can be reduced 
# to with the given operation 
def minLength(string, l) :
  
    # Stack to store the characters 
    # of the given string 
    s = []; 
  
    # For every character of the string 
    for i in range(l) :
  
        # If the stack is empty then push the 
        # current character in the stack 
        if (len(s) == 0) : 
            s.append(string[i]); 
              
        else :
  
            # Get the top character 
            c = s[-1];
              
            # If the top element is not equal 
            # to the current element and it 
            # only differs in the case 
            if (c != string[i] and 
                c.upper() == string[i].upper()) :
  
                # Pop the top element from stack 
                s.pop(); 
  
            # Else push the current element 
            else :
                s.append(string[i]);
  
    return len(s); 
  
# Driver code 
if __name__ == "__main__"
  
    string = "ASbBsd"
    l = len(string); 
  
    print(minLength(string, l));
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System; 
using System.Collections.Generic;
  
class GFG
{
  
// Function to return the minimum
// possible length str can be reduced
// to with the given operation
static int minLength(String str, int len)
{
  
    // Stack to store the characters
    // of the given string
    Stack<char> s = new Stack<char>();
  
    // For every character of the string
    for (int i = 0; i < len; i++) 
    {
  
        // If the stack is empty then push the
        // current character in the stack
        if (s.Count==0) 
        {
            s.Push(str[i]);
        }
        else
        {
  
            // Get the top character
            char c = s.Peek();
  
            // If the top element is not equal
            // to the current element and it
            // only differs in the case
            if (c != str[i] && 
                char.ToUpper(c) == 
                char.ToUpper((str[i]))) 
            {
  
                // Pop the top element from stack
                s.Pop();
            }
  
            // Else push the current element
            else
            {
                s.Push(str[i]);
            }
        }
    }
    return s.Count;
}
  
// Driver code
public static void Main(String []args) 
{
    String str = "ASbBsd";
    int len = str.Length;
  
    Console.WriteLine(minLength(str, len));
}
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.