Minimum replacements required to obtain a K-periodic palindromic string
Input: S = “abaaba”, K = 2
Explanation: The optimal way is to transform the string to “aaaaaa”. Therefore, the minimum number of changes required is 2.
Input: S = “aabbcbbcb”, K = 3
The optimal way is to transform the string to ”bcbbcbbcb”. Therefore, the minimum number of changes required is 2.
Approach: To minimize the number of changes required to make in the string, observe the following property of the transformed string which is palindromic and K-periodic:
- A K-periodic string can be made only by concatenating several palindromic strings having length K.
- All the characters at positions i, K – i – 1, i + K, 2K – i – 1, i + 2K, 3K – i – 1, i + 3K, … for all 0 ≤ i < K, are equal.
The problem reduces to making all the characters equal to the one which appears the maximum number of times at these positions in the given string. Follow the steps below to solve the above problem:
- Initialize a variable ans with 0 that stores the minimum changes required to satisfy the given condition.
- Iterate over the range [0, K / 2] using the variable i.
- Create a hashmap, mp to store the frequency of each character.
- Iterate over the characters in the string starting from i in intervals of K using a variable j and store the frequency of each character.
- Iterate the string in reverse, starting from (N – i – 1) in intervals of K using a variable j and store the frequency of each character. If K is odd and i = K / 2, then break out of the loop.
- Find the maximum frequency of a character among the visited one and store it in a variable, say curr_max.
- After the above steps, if K is odd and i = K/2, then increment ans by (N/K – curr_max)Otherwise, increment ans by (N/K – 2*curr_max).
- After the above steps, print the value of ans 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.