Minimum number of swaps to make two binary string equal | C ++ program for the above approach ; Function to calculate min swaps to make binary strings equal ; Count of zero 's ; Count of one 's ; As discussed above ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( string & s1 , string & s2 ) { int c0 = 0 , c1 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == '0' && s2 [ i ] == '1' ) { c0 ++ ; } else if ( s1 [ i ] == '1' && s2 [ i ] == '0' ) { c1 ++ ; } } int ans = c0 / 2 + c1 / 2 ; if ( c0 % 2 == 0 && c1 % 2 == 0 ) { return ans ; } else if ( ( c0 + c1 ) % 2 == 0 ) { return ans + 2 ; } else { return -1 ; } } int main ( ) { string s1 = "0011" , s2 = "1111" ; int ans = minSwaps ( s1 , s2 ) ; cout << ans << ' ' ; return 0 ; }