Minimum characters to be replaced to make a string concatenation of a K | Python3 program for the above approach ; Function to add an edge to graph ; Function to perform DFS traversal on the graph recursively from a given vertex u ; Visit the current vertex ; Total number of nodes in this component ; Increment the frequency of u ; Function for finding the minimum number changes required in given string ; Form the edges according to the given conditions ; Find minimum number of operations ; Frequency array for finding the most frequent character ; Frequency array for finding the most frequent character ; Finding most frequent character ; Change rest of the characters to most frequent one ; Print total number of changes ; Driver Code ; Function Call
import sys NEW_LINE sys . setrecursionlimit ( 1500 ) NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def DFS ( u , fre , S ) : NEW_LINE INDENT global visited , adj , cnt NEW_LINE visited [ u ] = 1 NEW_LINE cnt += 1 NEW_LINE fre [ ord ( S [ u ] ) - ord ( ' a ' ) ] += 1 NEW_LINE for i in adj [ u ] : NEW_LINE INDENT if ( visited [ i ] == 0 ) : NEW_LINE INDENT DFS ( i , fre , S ) NEW_LINE DEDENT DEDENT DEDENT def minimumOperations ( S , m ) : NEW_LINE INDENT global adj , visited , cnt NEW_LINE total , N = 0 , len ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT addEdge ( i , N - i - 1 ) NEW_LINE addEdge ( N - i - 1 , i ) NEW_LINE DEDENT for i in range ( N - m ) : NEW_LINE INDENT addEdge ( i , i + m ) NEW_LINE addEdge ( i + m , i ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT fre = [ 0 ] * 26 NEW_LINE cnt , maxx = 0 , - 1 NEW_LINE DFS ( i , fre , S ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT maxx = max ( maxx , fre [ j ] ) NEW_LINE DEDENT total += cnt - maxx NEW_LINE DEDENT DEDENT print ( total ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT adj = [ [ ] for i in range ( 101 ) ] NEW_LINE visited , cnt = [ 0 for i in range ( 101 ) ] , 0 NEW_LINE S = " abaaba " NEW_LINE K = 2 NEW_LINE minimumOperations ( S , K ) NEW_LINE DEDENT