Minimum number of bracket reversals needed to make an expression balanced | Set | 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 . ; To store number of reversals required . ; To store number of unbalanced opening brackets . ; To store number of unbalanced closing brackets . ; If current bracket is open then increment open count . ; If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; For the case : " } { " or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; Driver Code
function countMinReversals ( expr ) { var len = expr . length ; if ( len % 2 ) return - 1 ; var ans = 0 ; var i ; var open = 0 ; var close = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( expr [ i ] == ' ' ) open ++ ; else { if ( ! open ) close ++ ; else open -- ; } } ans = ( close / 2 ) + ( open / 2 ) ; close %= 2 ; open %= 2 ; if ( close ) ans += 2 ; return ans ; } var expr = " " ; document . write ( countMinReversals ( expr ) ) ;