Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
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 string “aaaaaa” is K-periodic and the periodic string “aa” is palindromic. Therefore, minimum changes required is 2.
Approach: The idea is to create a Graph from the given string indexes and perform DFS Traversals to find the required number of changes. Follow the below steps below to solve this problem:
- 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)
Please Login to comment...