Check if concatenation of two strings is balanced or not
Last Updated :
26 Aug, 2022
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 parenthesis 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 the stack then “not balanced”.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isBalanced(string s)
{
stack< char > st;
int n = s.length();
for ( int i = 0; i < n; i++) {
if (s[i] == '(' )
st.push(s[i]);
else {
if (st.empty()) {
return false ;
}
else
st.pop();
}
}
if (!st.empty())
return false ;
return true ;
}
bool isBalancedSeq(string s1, string s2)
{
if (isBalanced(s1 + s2))
return true ;
return isBalanced(s2 + s1);
}
int main()
{
string s1 = ")()(())))" ;
string s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
cout << "Balanced" ;
else
cout << "Not Balanced" ;
return 0;
}
|
Java
import java.util.Stack;
class GFG
{
static boolean isBalanced(String s)
{
Stack<Character> st = new Stack<Character>();
int n = s.length();
for ( int i = 0 ; i < n; i++)
{
if (s.charAt(i) == '(' )
{
st.push(s.charAt(i));
}
else if (st.empty())
{
return false ;
}
else
{
st.pop();
}
}
if (!st.empty())
{
return false ;
}
return true ;
}
static boolean isBalancedSeq(String s1, String s2)
{
if (isBalanced(s1 + s2))
{
return true ;
}
return isBalanced(s2 + s1);
}
public static void main(String[] args)
{
String s1 = ")()(())))" ;
String s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
{
System.out.println( "Balanced" );
}
else
{
System.out.println( "Not Balanced" );
}
}
}
|
Python3
def isBalanced(s):
st = list ()
n = len (s)
for i in range (n):
if s[i] = = '(' :
st.append(s[i])
else :
if len (st) = = 0 :
return False
else :
st.pop()
if len (st) > 0 :
return False
return True
def isBalancedSeq(s1, s2):
if (isBalanced(s1 + s2)):
return True
return isBalanced(s2 + s1)
if __name__ = = "__main__" :
s1 = ")()(())))"
s2 = "(()(()("
if isBalancedSeq(s1, s2):
print ( "Balanced" )
else :
print ( "Not Balanced" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool isBalanced(String s)
{
Stack< char > st = new Stack< char >();
int n = s.Length;
for ( int i = 0; i < n; i++)
{
if (s[i] == '(' )
{
st.Push(s[i]);
}
else if (st.Count==0)
{
return false ;
}
else
{
st.Pop();
}
}
if (st.Count!=0)
{
return false ;
}
return true ;
}
static bool isBalancedSeq(String s1, String s2)
{
if (isBalanced(s1 + s2))
{
return true ;
}
return isBalanced(s2 + s1);
}
public static void Main(String[] args)
{
String s1 = ")()(())))" ;
String s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
{
Console.WriteLine( "Balanced" );
}
else
{
Console.WriteLine( "Not Balanced" );
}
}
}
|
Javascript
<script>
function isBalanced(s)
{
let st = [];
let n = s.length;
for (let i = 0; i < n; i++)
{
if (s[i] == '(' )
{
st.push(s[i]);
}
else if (st.length == 0)
{
return false ;
}
else
{
st.pop();
}
}
if (st.length != 0)
{
return false ;
}
return true ;
}
function isBalancedSeq(s1, s2)
{
if (isBalanced(s1 + s2))
{
return true ;
}
return isBalanced(s2 + s1);
}
let s1 = ")()(())))" ;
let s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
{
document.write( "Balanced" );
}
else
{
document.write( "Not Balanced" );
}
</script>
|
Complexity Analysis:
- Time complexity: O(n)
- Auxiliary Space: O(n)
An efficient solution is to check if given sequences can result in a 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++
#include <bits/stdc++.h>
using namespace std;
bool isBalanced(string s)
{
int cnt = 0;
int n = s.length();
for ( int i = 0; i < n; i++) {
if (s[i] == '(' )
cnt++;
else {
cnt--;
if (cnt < 0)
return false ;
}
}
if (cnt > 0)
return false ;
return true ;
}
bool isBalancedSeq(string s1, string s2)
{
if (isBalanced(s1 + s2))
return true ;
return isBalanced(s2 + s1);
}
int main()
{
string s1 = ")()(())))" ;
string s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
cout << "Balanced" ;
else
cout << "Not Balanced" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean isBalanced(String s)
{
int cnt = 0 ;
int n = s.length();
for ( int i = 0 ; i < n; i++)
{
if (s.charAt(i) == '(' )
{
cnt = cnt + 1 ;
}
else
{
cnt = cnt - 1 ;
if (cnt < 0 )
return false ;
}
}
if (cnt > 0 )
return false ;
return true ;
}
static boolean isBalancedSeq(String s1,
String s2)
{
if (isBalanced(s1 + s2))
return true ;
return isBalanced(s2 + s1);
}
public static void main(String [] args)
{
String s1 = ")()(())))" ;
String s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
{
System.out.println( "Balanced" );
}
else
{
System.out.println( "Not Balanced" );
}
}
}
|
Python3
def isBalanced(s):
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)
a = ")()(())))" ;
b = "(()(()(" ;
if (isBalancedSeq(a, b)):
print ( "Balanced" )
else :
print ( "Not Balanced" )
|
C#
using System;
class GFG
{
static bool isBalanced(String s)
{
int cnt = 0;
int n = s.Length;
for ( int i = 0; i < n; i++)
{
if (s[i] == '(' )
{
cnt = cnt + 1;
}
else
{
cnt = cnt - 1;
if (cnt < 0)
return false ;
}
}
if (cnt > 0)
return false ;
return true ;
}
static bool isBalancedSeq(String s1,
String s2)
{
if (isBalanced(s1 + s2))
return true ;
return isBalanced(s2 + s1);
}
public static void Main()
{
String s1 = ")()(())))" ;
String s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
{
Console.WriteLine( "Balanced" );
}
else
{
Console.WriteLine( "Not Balanced" );
}
}
}
|
PHP
<?php
function isBalanced( $s )
{
$cnt = 0;
$n = strlen ( $s );
for ( $i = 0; $i < $n ; $i ++)
{
if ( $s [ $i ] == '(' )
$cnt ++;
else
{
$cnt --;
if ( $cnt < 0)
return false;
}
}
if ( $cnt > 0)
return false;
return true;
}
function isBalancedSeq( $s1 , $s2 )
{
if (isBalanced( $s1 + $s2 ))
return true;
return isBalanced( $s2 + $s1 );
}
$s1 = ")()(())))" ;
$s2 = "(()(()(" ;
if (!isBalancedSeq( $s1 , $s2 ))
echo "Balanced" ;
else
echo "Not Balanced" ;
?>
|
Javascript
<script>
function isBalanced(s)
{
var cnt = 0;
var n = s.length;
for ( var i = 0; i < n; i++) {
if (s[i] == '(' )
cnt++;
else {
cnt--;
if (cnt < 0)
return false ;
}
}
if (cnt > 0)
return false ;
return true ;
}
function isBalancedSeq(s1, s2)
{
if (isBalanced(s1 + s2))
return true ;
return isBalanced(s2 + s1);
}
var s1 = ")()(())))" ;
var s2 = "(()(()(" ;
if (isBalancedSeq(s1, s2))
document.write( "Balanced" );
else
document.write( "Not Balanced" );
</script>
|
Complexity Analysis:
- Time complexity: O(n)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...