Minimum replacements required to obtain a K | Python3 program for the above approach ; 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
import sys NEW_LINE def findMinimumChanges ( N , K , S ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( K + 1 ) // 2 ) : NEW_LINE INDENT mp = { } NEW_LINE for j in range ( i , N , K ) : NEW_LINE INDENT mp [ S [ j ] ] = mp . get ( S [ j ] , 0 ) + 1 NEW_LINE DEDENT j = N - i - 1 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( ( K & 1 ) and ( i == K // 2 ) ) : NEW_LINE INDENT break NEW_LINE DEDENT mp [ S [ j ] ] = mp . get ( S [ j ] , 0 ) + 1 NEW_LINE j -= K NEW_LINE DEDENT curr_max = - sys . maxsize - 1 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT curr_max = max ( curr_max , value ) NEW_LINE DEDENT if ( ( K & 1 ) and ( i == K // 2 ) ) : NEW_LINE INDENT ans += ( N // K - curr_max ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( N // K * 2 - curr_max ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aabbcbbcb " NEW_LINE N = len ( S ) NEW_LINE K = 3 NEW_LINE print ( findMinimumChanges ( N , K , S ) ) NEW_LINE DEDENT