Minimum swaps required to make a binary string alternating | returns the minimum number of swaps of a binary string passed as the argument to make it alternating ; counts number of zeroes at odd and even positions ; counts number of ones at odd and even positions ; alternating string starts with 0 ; alternating string starts with 1 ; calculates the minimum number of swaps ; Driver code
def countMinSwaps ( st ) : NEW_LINE INDENT min_swaps = 0 NEW_LINE odd_0 , even_0 = 0 , 0 NEW_LINE odd_1 , even_1 = 0 , 0 NEW_LINE n = len ( st ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT if st [ i ] == "1" : NEW_LINE INDENT even_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even_0 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if st [ i ] == "1" : NEW_LINE INDENT odd_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd_0 += 1 NEW_LINE DEDENT DEDENT DEDENT cnt_swaps_1 = min ( even_0 , odd_1 ) NEW_LINE cnt_swaps_2 = min ( even_1 , odd_0 ) NEW_LINE return min ( cnt_swaps_1 , cnt_swaps_2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "000111" NEW_LINE print ( countMinSwaps ( st ) ) NEW_LINE DEDENT