Minimum swaps required to make a binary string alternating | 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
def countMinSwaps ( s ) : NEW_LINE INDENT N = len ( s ) NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT DEDENT if ( one > zero + 1 or zero > one + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( N % 2 ) : NEW_LINE INDENT num = ( N + 1 ) / 2 NEW_LINE one_even = 0 NEW_LINE zero_even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT one_even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero_even += 1 NEW_LINE DEDENT DEDENT DEDENT if ( one > zero ) : NEW_LINE INDENT return num - one_even NEW_LINE DEDENT else : NEW_LINE INDENT return num - zero_even NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT one_odd = 0 NEW_LINE one_even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT one_odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT one_even += 1 NEW_LINE DEDENT DEDENT DEDENT return min ( N // 2 - one_odd , N // 2 - one_even ) NEW_LINE DEDENT DEDENT s = "111000" NEW_LINE print ( countMinSwaps ( s ) ) NEW_LINE