Minimum number of bracket reversals needed to make an expression balanced | Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; After this loop , stack contains unbalanced part of expression , i . e . , expression of the form " . . . . " ; Length of the reduced expression red_len = ( m + n ) ; count opening brackets at the end of stack ; return ceil ( m / 2 ) + ceil ( n / 2 ) which is actually equal to ( m + n ) / 2 + n % 2 when m + n is even . ; Driver Code
def countMinReversals ( expr ) : NEW_LINE INDENT lenn = len ( expr ) NEW_LINE if ( lenn % 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT s = [ ] NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( expr [ i ] == ' ' and len ( s ) ) : NEW_LINE INDENT if ( s [ 0 ] == ' ' ) : NEW_LINE INDENT s . pop ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT s . insert ( 0 , expr [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT s . insert ( 0 , expr [ i ] ) NEW_LINE DEDENT DEDENT red_len = len ( s ) NEW_LINE n = 0 NEW_LINE while ( len ( s ) and s [ 0 ] == ' ' ) : NEW_LINE INDENT s . pop ( 0 ) NEW_LINE n += 1 NEW_LINE DEDENT return ( red_len // 2 + n % 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT expr = " } } { { " NEW_LINE print ( countMinReversals ( expr . strip ( ) ) ) NEW_LINE DEDENT