Balance a string after removing extra brackets Last Updated : 01 Sep, 2022 Comments Improve Suggest changes Like Article Like Report Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it. Examples: Input: str = "gau)ra)v(ku(mar(rajput))" Output: gaurav(ku(mar(rajput))) Input: str = "1+5)+5+)6+(5+9)*9" Output: 1+5+5+6+(5+9)*9 Approach: Start traversing from left to right.Check if the element at current index is an opening bracket '(' then print that bracket and increment count.Check if the element at current index is a closing bracket ')' and if the count is not equal to zero then print it and decrement the count.Check if there is any element other than brackets at the current index in the string then print it.And in last if the count is not equal to zero then print ')' equal to the number of the count to balance the string. Below is the implementation of above approach: C++ // C++ implementation of above approach #include <bits/stdc++.h> using namespace std; // Print balanced and remove // extra brackets from string void balancedString(string str) { int count = 0, i; int n = str.length(); // Maintain a count for opening brackets // Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment count by 1 cout << str[i]; count++; } // check if closing bracket and count != 0 else if (str[i] == ')' && count != 0) { cout << str[i]; // decrement count by 1 count--; } // if str[i] not a closing brackets // print it else if (str[i] != ')') cout << str[i]; } // balanced brackets if opening brackets // are more then closing brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) cout << ")"; } // Driver code int main() { string str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); return 0; } Java // Java implementation of above approach class GFG { // Print balanced and remove // extra brackets from string public static void balancedString(String str) { int count = 0, i; int n = str.length(); // Maintain a count for opening brackets // Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str.charAt(i) == '(') { // print str.charAt(i) and increment count by 1 System.out.print(str.charAt(i)); count++; } // check if closing bracket and count != 0 else if (str.charAt(i) == ')' && count != 0) { System.out.print(str.charAt(i)); // decrement count by 1 count--; } // if str.charAt(i) not a closing brackets // print it else if (str.charAt(i) != ')') System.out.print(str.charAt(i)); } // balanced brackets if opening brackets // are more then closing brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) System.out.print(")"); } // Driver Method public static void main(String args[]) { String str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); } } Python3 # Python implementation of above approach # Print balanced and remove # extra brackets from string def balancedString(str): count, i = 0, 0 n = len(str) # Maintain a count for opening # brackets Traversing string for i in range(n): # check if opening bracket if (str[i] == '('): # print str[i] and increment # count by 1 print(str[i], end = "") count += 1 # check if closing bracket and count != 0 elif (str[i] == ')' and count != 0): print(str[i], end = "") # decrement count by 1 count -= 1 # if str[i] not a closing brackets # print it elif (str[i] != ')'): print(str[i], end = "") # balanced brackets if opening brackets # are more then closing brackets if (count != 0): # print remaining closing brackets for i in range(count): print(")", end = "") # Driver code if __name__ == '__main__': str = "gau)ra)v(ku(mar(rajput))" balancedString(str) # This code is contributed by 29AjayKumar C# // C# implementation of above approach using System; class GFG { // Print balanced and remove // extra brackets from string public static void balancedString(String str) { int count = 0, i; int n = str.Length; // Maintain a count for opening // brackets Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment // count by 1 Console.Write(str[i]); count++; } // check if closing bracket // and count != 0 else if (str[i] == ')' && count != 0) { Console.Write(str[i]); // decrement count by 1 count--; } // if str[i] not a closing // brackets print it else if (str[i] != ')') Console.Write(str[i]); } // balanced brackets if opening // brackets are more then closing // brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) Console.Write(")"); } // Driver Code public static void Main() { String str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); } } // This code is contributed // by PrinciRaj1992 PHP <?php // PHP implementation of above approach // Print balanced and remove // extra brackets from string function balancedString($str) { $count = 0; $n = strlen($str); // Maintain a count for opening // brackets Traversing string for ($i = 0; $i < $n; $i++) { // check if opening bracket if ($str[$i] == '(') { // print str[i] and increment // count by 1 echo $str[$i]; $count++; } // check if closing bracket and count != 0 else if ($str[$i] == ')' && $count != 0) { echo $str[$i]; // decrement count by 1 $count--; } // if str[i] not a closing brackets // print it else if ($str[$i] != ')') echo $str[$i]; } // balanced brackets if opening brackets // are more then closing brackets if ($count != 0) // print remaining closing brackets for ($i = 0; $i < $count; $i++) echo ")"; } // Driver code $str = "gau)ra)v(ku(mar(rajput))"; balancedString($str); // This code is contributed // by Akanksha Rai ?> JavaScript <script> // javascript implementation of above approach // Print balanced and remove // extra brackets from string function balancedString( str) { var count = 0, i; var n = str.length; // Maintain a count for opening // brackets Traversing string for (i = 0; i < n; i++) { // check if opening bracket if (str[i] == '(') { // print str[i] and increment // count by 1 document.write(str[i]); count++; } // check if closing bracket // and count != 0 else if (str[i] == ')' && count != 0) { document.write(str[i]); // decrement count by 1 count--; } // if str[i] not a closing // brackets print it else if (str[i] != ')') document.write(str[i]); } // balanced brackets if opening // brackets are more then closing // brackets if (count != 0) // print remaining closing brackets for (i = 0; i < count; i++) document.write(")"); } // Driver Code var str = "gau)ra)v(ku(mar(rajput))"; balancedString(str); // This code is contributed by bunnyram19. </script> Outputgaurav(ku(mar(rajput))) Complexity Analysis: Time Complexity: O(N), where N is the size of the given string.Auxiliary Space: O(1) as no extra space is being used. Comment More infoAdvertise with us Next Article Balance a string after removing extra brackets R rajput-ji Follow Improve Article Tags : Strings DSA Constructive Algorithms Practice Tags : Strings Similar Reads Maximum length of balanced string after swapping and removal of characters Given a string str consisting of characters '(', ')', '[', ']', '{' and '}' only. The task is to find the maximum length of the balanced string after removing any character and swapping any two adjacent characters.Examples: Input: str = "))[]]((" Output: 6 The string can be converted to ()[]()Input: 6 min read Minimum swaps to balance the given brackets at any index Given a balanced string of even length consisting of equal number of opening brackets â[â and closing brackets â]â , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represe 5 min read Find an equal point in a string of brackets Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. '(' and ')'.An equal point is an index such that the number of opening brackets be 7 min read Min Adjacent Swaps for Bracket Balancing You are given a string of 2N characters consisting of N '[' brackets and N ']' brackets. A string is considered balanced if it can be represented in the form S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum 15+ min read Print the balanced bracket expression using given brackets Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examp 6 min read Like