Minimum swaps required to make a binary string alternating | function to count minimum swaps required to make binary String alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length String ; number of even positions ; stores number of zeroes and ones at even positions ; even length String ; stores number of ones at odd and even position respectively ; Driver code
function countMinSwaps ( s ) { var N = s . length ; var one = 0 ; var zero = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == ' ' ) one ++ ; else zero ++ ; } if ( one > zero + 1 zero > one + 1 ) return - 1 ; if ( N % 2 == 1 ) { var num = ( N + 1 ) / 2 ; var one_even = 0 , zero_even = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { if ( s . charAt ( i ) == ' ' ) one_even ++ ; else zero_even ++ ; } } if ( one > zero ) return num - one_even ; else return num - zero_even ; } else { var one_odd = 0 , one_even = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == ' ' ) { if ( i % 2 == 1 ) one_odd ++ ; else one_even ++ ; } } return Math . min ( N / 2 - one_odd , N / 2 - one_even ) ; } } var s = " " ; document . write ( countMinSwaps ( s ) ) ;