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.
“(())”
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 the 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 balnced 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 balnced 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 balnced 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 balnced 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 |
Yes
Recommended Posts:
- Find the lexicographical next balanced bracket sequence
- Convert an unbalanced bracket sequence to a balanced sequence
- Find index of closing bracket for a given opening bracket in an expression
- Print the balanced bracket expression using given brackets
- Number of balanced bracket subsequence of length 2 and 4
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of bracket reversals needed to make an expression balanced
- Number of closing brackets needed to complete a regular bracket sequence
- Check if expression contains redundant bracket or not | Set 2
- Print Bracket Number
- Expression contains redundant bracket or not
- Minimum Swaps for Bracket Balancing
- Construct Binary Tree from String with bracket representation
- Print all ways to break a string in bracket form
- Range Queries for Longest Correct Bracket Subsequence
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.