human
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"
Solution in Python:
assistant
#Here is code to minimum swaps required to make a binary string alternating and the other steps required.
 def countMinSwaps ( s ) :
	N = len ( s )
	one = 0
	zero = 0
	for i in range ( N ) :
		if ( s [ i ] == '1' ) :
			one += 1
		else :
			zero += 1
	if ( one > zero + 1 or zero > one + 1 ) :
		return - 1
	if ( N % 2 ) :
		num = ( N + 1 ) / 2
		one_even = 0
		zero_even = 0
		for i in range ( N ) :
			if ( i % 2 == 0 ) :
				if ( s [ i ] == '1' ) :
					one_even += 1
				else :
					zero_even += 1
		if ( one > zero ) :
			return num - one_even
		else :
			return num - zero_even
	else :
		one_odd = 0
		one_even = 0
		for i in range ( N ) :
			if ( s [ i ] == '1' ) :
				if ( i % 2 ) :
					one_odd += 1
				else :
					one_even += 1
		return min ( N // 2 - one_odd , N // 2 - one_even )
s = "111000"
print ( countMinSwaps ( s ) )