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
< ? php function countMinSwaps ( $ st ) { $ min_swaps = 0 ; $ odd_0 = 0 ; $ even_0 = 0 ; $ odd_1 = 0 ; $ even_1 = 0 ; $ n = strlen ( $ st ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i % 2 == 0 ) { if ( $ st [ $ i ] == '1' ) { $ even_1 ++ ; } else { $ even_0 ++ ; } } else { if ( $ st [ $ i ] == '1' ) { $ odd_1 ++ ; } else { $ odd_0 ++ ; } } } $ cnt_swaps_1 = min ( $ even_0 , $ odd_1 ) ; $ cnt_swaps_2 = min ( $ even_1 , $ odd_0 ) ; return min ( $ cnt_swaps_1 , $ cnt_swaps_2 ) ; } $ st = "000111" ; echo ( countMinSwaps ( $ st ) ) ; ? >