Check if the bracket sequence can be balanced with at most one change in the position of a bracket Last Updated : 13 Jul, 2022 Comments Improve Suggest changes Like Article Like Report Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: Consider X as a valid bracket then definitely (X) is also valid. If X is not valid and can be balanced with just one change of position in some bracket then it must be of type X = ")(" where ')' has been placed before '('. Now, X can be replaced with (X) as it will not affect the balanced nature of X. The new string becomes X = "()()" which is balanced. Hence, if (X) is balanced then we can say that X can be balanced with at most one change in the position of some bracket.Below is the implementation of the above approach: C++ // CPP implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket bool canBeBalanced(string s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = "("; k += s + ")"; vector<string> d; int cnt = 0; for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push_back("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.pop_back(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.empty()) return true; return false; } // Driver Code int main(int argc, char const *argv[]) { string s = ")(()"; int n = s.length(); (canBeBalanced(s, n)) ? cout << "Yes" << endl : cout << "No" << endl; return 0; } // This code is contributed by // sanjeev2552 Java // Java implementation of the approach import java.util.Vector; class GFG { // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static boolean canBeBalanced(String s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string String k = "("; k += s + ")"; Vector<String> d = new Vector<>(); for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k.charAt(i) == '(') d.add("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.remove(d.size() - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.isEmpty()) return true; return false; } // Driver Code public static void main(String[] args) { String s = ")(()"; int n = s.length(); if (canBeBalanced(s, n)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by // sanjeev2552 Python3 # Python3 implementation of the approach # Function that returns true if the sequence # can be balanced by changing the # position of at most one bracket def canBeBalanced(s, n): # Odd length string can # never be balanced if n % 2 == 1: return False # Add '(' in the beginning and ')' # in the end of the string k = "(" k = k + s+")" d = [] count = 0 for i in range(len(k)): # If its an opening bracket then # append it to the temp string if k[i] == "(": d.append("(") # If its a closing bracket else: # There was an opening bracket # to match it with if len(d)!= 0: d.pop() # No opening bracket to # match it with else: return False # Sequence is balanced if len(d) == 0: return True return False # Driver code S = ")(()" n = len(S) if(canBeBalanced(S, n)): print("Yes") else: print("No") C# // C# implementation of the approach using System; using System.Collections.Generic; class GFG { // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static bool canBeBalanced(string s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = "("; k += s + ")"; List<string> d = new List<string>(); for (int i = 0; i < k.Length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.Add("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.Count != 0) d.RemoveAt(d.Count - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.Count == 0) return true; return false; } // Driver Code public static void Main() { string s = ")(()"; int n = s.Length; if (canBeBalanced(s, n)) Console.Write("Yes"); else Console.Write("No"); } } // This code is contributed by // mohit kumar 29 JavaScript <script> // JavaScript implementation of the approach // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket function canBeBalanced(s,n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string let k = "("; k += s + ")"; let d = []; for (let i = 0; i < k.length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.length != 0) d.pop(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.length==0) return true; return false; } // Driver Code let s = ")(()"; let n = s.length; if (canBeBalanced(s, n)) document.write("Yes"); else document.write("No"); // This code is contributed by unknown2108 </script> Output: Yes Time Complexity : O(n) ,where n is size of given string Space Complexity : O(n) Comment More infoAdvertise with us Next Article Number of closing brackets needed to complete a regular bracket sequence D divyamohan123 Follow Improve Article Tags : Strings DSA Constructive Algorithms Practice Tags : Strings Similar Reads Mastering Bracket Problems for Competitive Programming Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec 4 min read Check for balanced with only one type of brackets Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples:Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initialis 9 min read Valid Parentheses in an Expression Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.Exa 8 min read Length of longest balanced parentheses prefix Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6The idea is take value of op 9 min read Modify a numeric string to a balanced parentheses by replacements Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the 10 min read Check if the bracket sequence can be balanced with at most one change in the position of a bracket Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "( 6 min read Number of closing brackets needed to complete a regular bracket sequence Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete th 7 min read Minimum number of Parentheses to be added to make it valid Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: s 9 min read Minimum bracket reversals to make an expression balanced Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation: 15+ min read Find the number of valid parentheses expressions of given length Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp 11 min read Like