text: Minimum replacements required to obtain a K | Function to find the minimum number of changes to make the string K - periodic and palindrome ; Initialize ans with 0 ; Iterate from 0 to ( K + 1 ) / 2 ; Store frequency of character ; Iterate through all indices , i , i + K , i + 2 k ... . and store the frequency of character ; Increase the frequency of current character ; Iterate through all indices K - i , 2 K - i , 3 K - i ... . and store the frequency of character ; If K is odd & i is samw as K / 2 , break the loop ; Increase the frequency of current character ; Find the maximum frequency of a character among all visited characters ; If K is odd and i is same as K / 2 then , only N / K characters is visited ; Otherwise N / K * 2 characters has visited ; Return the result ; Driver Code ; Function Call
code: function findMinimumChanges ( N , K , S ) { var ans = 0 ; for ( var i = 0 ; i < parseInt ( ( K + 1 ) / 2 ) ; i ++ ) { var mp = new Map ( ) ; for ( var j = i ; j < N ; j += K ) { if ( mp . has ( S [ j ] ) ) { mp . set ( S [ j ] , mp . get ( S [ j ] ) + 1 ) ; } else { mp . set ( S [ j ] , 1 ) ; } } for ( var j = N - i - 1 ; j >= 0 ; j -= K ) { if ( ( K & 1 ) && i == parseInt ( K / 2 ) ) break ; if ( mp . has ( S [ j ] ) ) { mp . set ( S [ j ] , mp . get ( S [ j ] ) + 1 ) ; } else { mp . set ( S [ j ] , 1 ) ; } } var curr_max = - 1000000000 ; mp . forEach ( ( value , key ) => { curr_max = Math . max ( curr_max , value ) ; } ) ; if ( K & 1 && i == parseInt ( K / 2 ) ) ans += ( parseInt ( N / K ) - curr_max ) ; else ans += ( parseInt ( N / K ) * 2 - curr_max ) ; } return ans ; } var S = " " ; var N = S . length ; var K = 3 ; document . write ( findMinimumChanges ( N , K , S ) ) ;