Minimum swaps required to make a binary string alternating | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSwaps ( string s ) { int N = s . size ( ) ; int one = 0 ; int zero = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) one ++ ; else zero ++ ; } if ( one > zero + 1 zero > one + 1 ) return -1 ; if ( N % 2 ) { 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 [ 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 [ i ] == '1' ) { if ( i % 2 ) one_odd ++ ; else one_even ++ ; } } return min ( N / 2 - one_odd , N / 2 - one_even ) ; } } int main ( ) { string s = "111000" ; cout << countMinSwaps ( s ) ; return 0 ; }