human
Minimum adjacent swaps required to make a binary string alternating | Function to find the minimum number of adjacent swaps to make the string alternating.
Count the no of zeros and ones.
Base Case.
Store no of min swaps when string starts with "1".
Keep track of the odd positions.
Checking for when the string starts with "1".
Adding the no of swaps to fix "1" at odd positions.
Store no of min swaps when string starts with "0".
Keep track of the odd positions.
Checking for when the string starts with "0".
Adding the no of swaps to fix "1" at odd positions.
Returning the answer based on the conditions when string length is even.
When string length is odd.
When no of ones is greater than no of zeros.
When no of ones is greater than no of zeros.
Driver Code"
Solution in Python:
 Write me a code to minimum adjacent swaps required to make a binary string alternating and the other steps required?
assistant
#Here is code to minimum adjacent swaps required to make a binary string alternating and the other steps required.
 def minSwaps ( s ) :
	ones = 0
	zeros = 0
	N = len ( s )
	for i in range ( N ) :
		if s [ i ] == '1' :
			ones += 1
		else :
			zeros += 1
	if ( ( N % 2 == 0 and ones != zeros ) or ( N % 2 == 1 and abs ( ones - zeros ) != 1 ) ) :
		return - 1
	ans_1 = 0
	j = 0
	for i in range ( N ) :
		if ( s [ i ] == '1' ) :
			ans_1 += abs ( j - i )
			j += 2
	ans_0 = 0
	k = 0
	for i in range ( N ) :
		if ( s [ i ] == '0' ) :
			ans_0 += abs ( k - i )
			k += 2
	if ( N % 2 == 0 ) :
		return min ( ans_1 , ans_0 )
	else :
		if ( ones > zeros ) :
			return ans_1
		else :
			return ans_0
if __name__ == ' _ _ main _ _ ' :
	S = "110100"
	print ( minSwaps ( S ) )