Given two bracket sequences S1 and S2 consisting of ‘(‘ and ‘)’. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1.

**Examples:**

Input:s1 = “)()(())))”, s2 = “(()(()(”

Output:Balanced

s2 + s1 = “(()(()()()(())))”, which

is a balanced paranthesis sequence.

Input:s1 = “(()))(“, s2 = “())())”

Output:Not balanced

s1 + s2 = “(()))(())())” –> Not balanced

s2 + s1 = “())())(()))(” –> Not balanced

A **naive** solution is to first concatenate both sequences and then check if the resultant sequence is balanced or not using a stack. First, check if s1 + s2 is balanced or not. If not, then check if s2 + s1 is balanced or not. To check if a given sequence of brackets is balanced or not using a stack, the following algorithm can be used.

- Declare a character stack S.
- Now traverse the expression string exp.
- If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
- If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.

- After complete traversal, if there is some starting bracket left in stack then “not balanced”.

Below is the implementation of above approach:

## C++

// CPP program to check if sequence obtained // by concatenating two bracket sequences // is balanced or not. #include <bits/stdc++.h> using namespace std; // Check if given string is balanced bracket // sequence or not. bool isBalanced(string s) { stack<char> st; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') st.push(s[i]); // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else { if (st.empty()) { return false; } else st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (!st.empty()) return false; return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. bool isBalancedSeq(string s1, string s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. int main() { string s1 = ")()(())))"; string s2 = "(()(()("; if (isBalancedSeq(s1, s2)) cout << "Balanced"; else cout << "Not Balanced"; return 0; }

**Output:**

Balanced

**Time complexity:** O(n)

**Auxiliary Space:** O(n)

An **efficient** solution is to check if given sequences can result in balanced parenthesis sequence without using a stack, i.e., in constant extra space.

Let the concatenated sequence is s. There are two possibilities: either s = s1 + s2 is balanced or s = s2 + s1 is balanced. Check for both possibilities whether s is balanced or not.

- If s is balanced, then the number of opening brackets in s should always be greater than or equal to the number of closing brackets in S at any instant of traversing it. This is because if at any instant number of closing brackets in s is greater than the number of opening brackets, then the last closing bracket will not have a matching opening bracket (that is why the count is more) in s.
- If the sequence is balanced then at the end of traversal, the number of opening brackets in s is equal to the number of closing brackets in s.

Below is the implementation of above approach:

## C++

// C++ program to check if sequence obtained // by concatenating two bracket sequences // is balanced or not. #include <bits/stdc++.h> using namespace std; // Check if given string is balanced bracket // sequence or not. bool isBalanced(string s) { // To store result of comparison of // count of opening brackets and // closing brackets. int cnt = 0; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an // opening bracket, then // increment count. if (s[i] == '(') cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt--; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. bool isBalancedSeq(string s1, string s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. int main() { string s1 = ")()(())))"; string s2 = "(()(()("; if (isBalancedSeq(s1, s2)) cout << "Balanced"; else cout << "Not Balanced"; return 0; }

## Java

// Java program to check if // sequence obtained by // concatenating two bracket // sequences is balanced or not. import java.io.*; class GFG { // Check if given string // is balanced bracket // sequence or not. static boolean isBalanced(String s) { // To store result of comparison // of count of opening brackets // and closing brackets. int cnt = 0; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is // an opening bracket, // then increment count. if (s.charAt(i) =='(') { cnt = cnt + 1; } // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt = cnt - 1; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true; } // Function to check if string // obtained by concatenating // two bracket sequences is // balanced or not. static boolean isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is // balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is // balanced or not. return isBalanced(s2 + s1); } // Driver code public static void main(String [] args) { String s1 = ")()(())))"; String s2 = "(()(()("; if (isBalancedSeq(s1, s2)) { System.out.println("Balanced"); } else { System.out.println("Not Balanced"); } } } // This code is contributed // by Shivi_Aggarwal

## Python3

# Python3 program to check # if sequence obtained by # concatenating two bracket # sequences is balanced or not. # Check if given string # is balanced bracket # sequence or not. def isBalanced(s): # To store result of # comparison of count # of opening brackets # and closing brackets. cnt = 0 n = len(s) for i in range(0, n): if (s[i] == '('): cnt = cnt + 1 else : cnt = cnt - 1 if (cnt < 0): return False if (cnt > 0): return False return True def isBalancedSeq(s1, s2): if (isBalanced(s1 + s2)): return True return isBalanced(s2 + s1) # Driver code a = ")()(())))"; b = "(()(()("; if (isBalancedSeq(a, b)): print("Balanced") else: print("Not Balanced") # This code is contributed # by Shivi_Aggarwal

**Output:**

Balanced

**Time complexity:** O(n)

**Auxiliary Space:** O(1)

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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.