Minimum swaps to balance the given brackets at any index | Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; Driver code
function BalancedStringBySwapping ( s ) { var unbalancedPair = 0 ; for ( var i = 0 ; i < s . length ; ++ i ) { if ( unbalancedPair > 0 && s [ i ] == ' ' ) { -- unbalancedPair ; } else if ( s [ i ] == ' ' ) { ++ unbalancedPair ; } } return ( unbalancedPair + 1 ) / 2 ; } var s = " " ; document . write ( BalancedStringBySwapping ( s ) ) ;