Minimum swaps required to make a binary string alternating | returns the minimum number of swaps of a binary string passed as the argument to make it alternating ; counts number of zeroes at odd and even positions ; counts number of ones at odd and even positions ; alternating string starts with 0 ; alternating string starts with 1 ; calculates the minimum number of swaps ; Driver code
function countMinSwaps ( st ) { let min_swaps = 0 ; let odd_0 = 0 , even_0 = 0 ; let odd_1 = 0 , even_1 = 0 ; let n = st . length ; for ( let i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { if ( st [ i ] == ' ' ) { even_1 ++ ; } else { even_0 ++ ; } } else { if ( st [ i ] == ' ' ) { odd_1 ++ ; } else { odd_0 ++ ; } } } let cnt_swaps_1 = Math . min ( even_0 , odd_1 ) ; let cnt_swaps_2 = Math . min ( even_1 , odd_0 ) ; return Math . min ( cnt_swaps_1 , cnt_swaps_2 ) ; } let st = " " ; document . write ( countMinSwaps ( st ) ) ;