text: Minimum Swaps for Bracket Balancing | Function to calculate swaps required ; Keep track of ' [ ' ; To count number of encountered ' [ ' ; To track position of next ' [ ' in pos ; To store result ; Increment count and move p to next position ; We have encountered an unbalanced part of string ; Increment sum by number of swaps required i . e . position of next ' [ ' - current position ; Reset count to 1 ; Driver Code
code: function swapCount ( s ) { let pos = [ ] ; for ( let i = 0 ; i < s . length ; ++ i ) if ( s [ i ] == ' ' ) pos . push ( i ) ; let count = 0 ; let p = 0 ; let sum = 0 ; let S = s . split ( ' ' ) ; for ( let i = 0 ; i < s . length ; ++ i ) { if ( S [ i ] == ' ' ) { ++ count ; ++ p ; } else if ( S [ i ] == ' ' ) -- count ; if ( count < 0 ) { sum += pos [ p ] - i ; let temp = S [ i ] ; S [ i ] = S [ pos [ p ] ] ; S [ pos [ p ] ] = temp ; ++ p ; count = 1 ; } } return sum ; } let s = " " ; document . write ( swapCount ( s ) + " " ) ; s = " " ; document . write ( swapCount ( s ) ) ;