human
Write me a code to minimize hamming distance in Binary String by setting only one K size substring bits and the other steps required given the following:
Minimize hamming distance in Binary String by setting only one K size substring bits | Function to find minimum Hamming Distance after atmost one operation.
Store the size of the string.
Store the prefix sum of 1 s.
Create Prefix Sum array.
Initialize cnt as number of ones in string S.
Store the required result.
Traverse the string , S.
Store the number of 1 s in the substring S [ i , i + K - 1 ].
Update the answer.
Return the result.
Driver Code.
Given Input.
Function Call"
Solution in Python:
assistant
#Here is code to minimize hamming distance in Binary String by setting only one K size substring bits and the other steps required.
 def minimumHammingDistance ( S , K ) :
	n = len ( S )
	pref = [ 0 ] * n
	pref [ 0 ] = ord ( S [ 0 ] ) - ord ( '0' )
	for i in range ( 1 , n ) :
		pref [ i ] = pref [ i - 1 ] + ( ord ( S [ i ] ) - ord ( '0' ) )
	cnt = pref [ n - 1 ]
	ans = cnt
	for i in range ( n - K ) :
		value = pref [ i + K - 1 ] - ( pref [ i - 1 ] if ( i - 1 ) >= 0 else 0 )
		ans = min ( ans , cnt - value + ( K - value ) )
	return ans
if __name__ == ' _ _ main _ _ ' :
	s = "101"
	K = 2
	print ( minimumHammingDistance ( s , K ) )