Minimum swaps required to make a binary string alternating | Java implementation of the above approach ; 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
import java . util . * ; class GFG { static int countMinSwaps ( String s ) { int N = s . length ( ) ; int one = 0 ; int zero = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '1' ) one ++ ; else zero ++ ; } if ( one > zero + 1 zero > one + 1 ) return - 1 ; if ( N % 2 == 1 ) { int num = ( N + 1 ) / 2 ; int one_even = 0 , zero_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { if ( s . charAt ( i ) == '1' ) one_even ++ ; else zero_even ++ ; } } if ( one > zero ) return num - one_even ; else return num - zero_even ; } else { int one_odd = 0 , one_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '1' ) { if ( i % 2 == 1 ) one_odd ++ ; else one_even ++ ; } } return Math . min ( N / 2 - one_odd , N / 2 - one_even ) ; } } public static void main ( String [ ] args ) { String s = "111000" ; System . out . print ( countMinSwaps ( s ) ) ; } }