Minimize removal of non-equal adjacent characters required to make a given string empty

• Last Updated : 29 Apr, 2021

Given a string S consisting of ‘(‘ and ‘)’, the task is to find the minimum count of bracket reversals required to make the string an empty string by repeatedly removing a pair of non-equal adjacent characters. If it is not possible to empty the string, then print -1.

Examples:

Input: S = “)))(((“
Output: 0
Explanation:
Removing (S, S) from S modifies S to “))((“.
Removing (S, S) from S modifies S to “)(“.
Removing (S, S) from S modifies S to “”.
Since no flips are required to make S empty.
Therefore, the required output is 0.

Input: S = “))(“
Output: -1

Approach: Follow the steps below to solve the problem:

• Initialize two integer variables cnt1 and cnt2 as 0.
• If the length of the string is odd or only one type of character is present, then print “-1”.
• Otherwise, iterate over the characters of the string S and if the current character is ‘(‘, then increment the cnt1 by one. Otherwise, increment cnt2 by 1.
• After completing the above steps, print the value of abs(cnt1 – cnt2)/2 as the minimum number of reversals required.

Below is the implementation of the above approach:

C++

 // C++ program for the above approach#include using namespace std; // Function to find minimum count of steps// required ot make string S an empty stringvoid canReduceString(string S, int N){     // Stores count of occurences '('    int count_1 = 0;     // Stores count of occurences ')'    int count_2 = 0;     // Traverse the string, str    for (int i = 0; i < N; i++) {         // If current character is '('        if (S[i] == '(') {             // Update count_1            count_1++;        }        else {             // Update count_2            count_2++;        }    }     // If all the characters are    // same, then print -1    if (count_1 == 0 || count_2 == 0) {        cout << "-1" << endl;    }     // If the count of occurence of ')'    // and '(' are same then print 0    else if (count_1 == count_2) {        cout << "0" << endl;    }     // If length of string is Odd    else if (N % 2 != 0) {        cout << "-1";    }     else {        cout << abs(count_1 - count_2) / 2;    }} // Driver Codeint main(){     // Given string    string S = ")))(((";     // Size of the string    int N = S.length();     // Function Call    canReduceString(S, N);     return 0;}

Java

 // Java program for the above approachimport java.util.*; class GFG{ // Function to find minimum count of steps// required ot make String S an empty Stringstatic void canReduceString(String S, int N){         // Stores count of occurences '('    int count_1 = 0;     // Stores count of occurences ')'    int count_2 = 0;     // Traverse the String, str    for(int i = 0; i < N; i++)    {                 // If current character is '('        if (S.charAt(i) == '(')        {                         // Update count_1            count_1++;        }        else        {                         // Update count_2            count_2++;        }    }     // If all the characters are    // same, then print -1    if (count_1 == 0 || count_2 == 0)    {        System.out.print("-1" + "\n");    }     // If the count of occurence of ')'    // and '(' are same then print 0    else if (count_1 == count_2)    {        System.out.print("0" + "\n");    }     // If length of String is Odd    else if (N % 2 != 0)    {        System.out.print("-1");    }     else    {        System.out.print(Math.abs(            count_1 - count_2) / 2);    }} // Driver Codepublic static void main(String[] args){         // Given String    String S = ")))(((";     // Size of the String    int N = S.length();     // Function Call    canReduceString(S, N);}} // This code is contributed by shikhasingrajput

Python3

 #Python3 program for the above approach  # Function to find minimum count of steps# required ot make string S an empty stringdef canReduceString(S, N):     # Stores count of occurences '('    count_1 = 0     # Stores count of occurences ')'    count_2 = 0     # Traverse the string, str    for i in range(N):         # If current character is '('        if (S[i] == '('):             # Update count_1            count_1 += 1        else:             #Update count_2            count_2 += 1     # If all the characters are    # same, then pr-1    if (count_1 == 0 or count_2 == 0):        print("-1")         # If the count of occurence of ')'    # and '(' are same then pr0    elif (count_1 == count_2):        print("0")     # If length of string is Odd    elif (N % 2 != 0):        print("-1")    else:        print (abs(count_1 - count_2) // 2) # Driver Codeif __name__ == '__main__':     # Given string    S = ")))((("     # Size of the string    N = len(S)     # Function Call    canReduceString(S, N)     # This code is contributed by mohit kumar 29

C#

 // C# program for the above approachusing System; class GFG{ // Function to find minimum count of steps// required ot make String S an empty Stringstatic void canReduceString(String S, int N){         // Stores count of occurences '('    int count_1 = 0;         // Stores count of occurences ')'    int count_2 = 0;         // Traverse the String, str    for(int i = 0; i < N; i++)    {                 // If current character is '('        if (S[i] == '(')        {                         // Update count_1            count_1++;        }        else        {                         // Update count_2            count_2++;        }    }         // If all the characters are    // same, then print -1    if (count_1 == 0 || count_2 == 0)    {        Console.Write("-1" + "\n");    }         // If the count of occurence of ')'    // and '(' are same then print 0    else if (count_1 == count_2)    {        Console.Write("0" + "\n");    }         // If length of String is Odd    else if (N % 2 != 0)    {        Console.Write("-1");    }     else    {        Console.Write(Math.Abs(            count_1 - count_2) / 2);    }} // Driver Codepublic static void Main(String[] args){         // Given String    String S = ")))(((";     // Size of the String    int N = S.Length;     // Function Call    canReduceString(S, N);}} // This code is contributed by shikhasingrajput

Javascript


Output:
0

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

My Personal Notes arrow_drop_up