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 ; Given Input ; Function Call
function minimumHammingDistance ( S , K ) { let n = S . length ; let pref = new Array ( n ) ; pref [ 0 ] = S [ 0 ] - ' ' ; for ( let i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + ( S [ i ] - ' ' ) ; let cnt = pref [ n - 1 ] ; let ans = cnt ; for ( let i = 0 ; i < n - K ; i ++ ) { let value = pref [ i + K - 1 ] - ( i - 1 >= 0 ? pref [ i - 1 ] : 0 ) ; ans = Math . min ( ans , cnt - value + ( K - value ) ) ; } return ans ; } let s = " " ; let K = 2 ; document . write ( minimumHammingDistance ( s , K ) ) ;