Given a string S of size N and a positive integer K ( where N % K = 0), the task is to find the minimum number of characters required to be replaced such that the string is K-periodic and the K-length periodic string must be a palindrome.
Input: S = “abaaba”, K = 3
Explanation: The given string is already K-periodic and the periodic string “aba” is palindromic.
Input: S = “abaaba”, K = 2
Explanation: By changing the characters at index 1 and 4 to ‘a’, the updated sting “aaaaaa” is K-periodic and the periodic string “aa” is palindromic. Therefore, minimum changes required is 2.
- Initialize a variable total as 0 to store the count of changes required.
- According to the given conditions, create a graph from the string and in the final string all characters at positions i, K − i +1, K + i, 2K − i +1, 2K + i, 3K − i + 1, … for all 1 ≤ i ≤ K should be equal.
- Iterate over the range [0, N] and add an undirected edge between index i and (N – i – 1).
- Iterate over the range [0, N – M] and add an undirected edge between index i and (i + K).
- To minimize the required number of operations, make all the letters equal to the one which appears at these positions the most, which can be easily found by performing DFS Traversal on the string.
- Perform the DFS Traversal on the created graph for all unvisited nodes:
- Find the maximum element with the maximum frequency among the visited characters in that traversal(say maxFrequency).
- Update the total number of changes in characters by the difference of count of all visited characters in the DFS Traversal and the maximum frequency in the above step.
- After completing the above steps, print the value of the total as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.