Check if concatenation of two strings is balanced or not | Check if given string is balanced bracket sequence or not . ; If current bracket is an opening bracket push it to stack . ; 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 . ; If stack is not empty , then sequence is not balanced . ; Function to check if string obtained by concatenating two bracket sequences is balanced or not . ; Check if s1 + s2 is balanced or not . ; Check if s2 + s1 is balanced or not . ; Driver Code
def isBalanced ( s ) : NEW_LINE INDENT st = list ( ) NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] == ' ( ' : NEW_LINE INDENT st . append ( s [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( st ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT DEDENT DEDENT if len ( st ) > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def isBalancedSeq ( s1 , s2 ) : NEW_LINE INDENT if ( isBalanced ( s1 + s2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return isBalanced ( s2 + s1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : s1 = " ) ( ) ( ( ) ) ) ) " NEW_LINE INDENT s2 = " ( ( ) ( ( ) ( " NEW_LINE if isBalancedSeq ( s1 , s2 ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Balanced " ) NEW_LINE DEDENT DEDENT