Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Function that returns true if the sequence can be balanced by changing the position of at most one bracket ; Odd length string can never be balanced ; Add ' ( ' in the beginning and ' ) ' in the end of the string ; If its an opening bracket then append it to the temp string ; If its a closing bracket ; There was an opening bracket to match it with ; No opening bracket to match it with ; Sequence is balanced ; Driver code
def canBeBalanced ( s , n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT k = " ( " k = k + s + " ) " NEW_LINE d = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( len ( k ) ) : NEW_LINE INDENT if k [ i ] == " ( " : NEW_LINE INDENT d . append ( " ( " ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( d ) != 0 : NEW_LINE INDENT d . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if len ( d ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT S = " ) ( ( ) " NEW_LINE n = len ( S ) NEW_LINE if ( canBeBalanced ( S , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT