text: Minimum Swaps for Bracket Balancing | Javascript Program to count swaps required to balance string ; stores the total number of Left and Right brackets encountered ; swap stores the number of swaps required imbalance maintains the number of imbalance pair ; increment count of Left bracket ; swaps count is last swap count + total number imbalanced brackets ; imbalance decremented by 1 as it solved only one imbalance of Left and Right ; increment count of Right bracket ; imbalance is reset to current difference between Left and Right brackets ; Driver code
code: function swapCount ( s ) { let chars = s . split ( ' ' ) ; let countLeft = 0 , countRight = 0 ; let swap = 0 , imbalance = 0 ; for ( let i = 0 ; i < chars . length ; i ++ ) { if ( chars [ i ] == ' ' ) { countLeft ++ ; if ( imbalance > 0 ) { swap += imbalance ; imbalance -- ; } } else if ( chars [ i ] == ' ' ) { countRight ++ ; imbalance = ( countRight - countLeft ) ; } } return swap ; } let s = " " ; document . write ( swapCount ( s ) + " " ) ; s = " " ; document . write ( swapCount ( s ) ) ;