Minimum swaps required to make a binary string alternating | Java implementation of the approach ; 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
class GFG { static int countMinSwaps ( String st ) { int min_swaps = 0 ; int odd_0 = 0 , even_0 = 0 ; int odd_1 = 0 , even_1 = 0 ; int n = st . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { if ( st . charAt ( i ) == '1' ) even_1 ++ ; else even_0 ++ ; } else { if ( st . charAt ( i ) == '1' ) odd_1 ++ ; else odd_0 ++ ; } } int cnt_swaps_1 = Math . min ( even_0 , odd_1 ) ; int cnt_swaps_2 = Math . min ( even_1 , odd_0 ) ; return Math . min ( cnt_swaps_1 , cnt_swaps_2 ) ; } public static void main ( String [ ] args ) { String st = "000111" ; System . out . println ( countMinSwaps ( st ) ) ; } }