Minimum adjacent swaps required to make a binary string alternating | Java program for the above approach ; Function to find the minimum number of adjacent swaps to make the String alternating ; Count the no of zeros and ones ; Base Case ; Store no of min swaps when String starts with "1" ; Keep track of the odd positions ; Checking for when the String starts with "1" ; Adding the no of swaps to fix "1" at odd positions ; Store no of min swaps when String starts with "0" ; Keep track of the odd positions ; Checking for when the String starts with "0" ; Adding the no of swaps to fix "1" at odd positions ; Returning the answer based on the conditions when String length is even ; When String length is odd ; When no of ones is greater than no of zeros ; When no of ones is greater than no of zeros ; Driver Code
import java . util . * ; class GFG { static int minSwaps ( String s ) { int ones = 0 , zeros = 0 ; int N = s . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '1' ) ones ++ ; else zeros ++ ; } if ( ( N % 2 == 0 && ones != zeros ) || ( N % 2 == 1 && Math . abs ( ones - zeros ) != 1 ) ) { return - 1 ; } int ans_1 = 0 ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '1' ) { ans_1 += Math . abs ( j - i ) ; j += 2 ; } } int ans_0 = 0 ; int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '0' ) { ans_0 += Math . abs ( k - i ) ; k += 2 ; } } if ( N % 2 == 0 ) return Math . min ( ans_1 , ans_0 ) ; else { if ( ones > zeros ) return ans_1 ; else return ans_0 ; } } public static void main ( String [ ] args ) { String S = "110100" ; System . out . print ( minSwaps ( S ) ) ; } }