Given a string S of length N consisting of lowercase letters and an integer K, where N % K = 0, the task is to find the minimum cost to convert the given string into a concatenated string of same K-length substrings by performing the following operations:
- A character can be replaced with another character.
- Cost of each operation is the absolute difference between the replacced and the replacing character. For example, if ‘a’ is replaced with ‘z’, then cost of the operation is |”a”-“z”| = 25.
Input: S = “abcdef”, K = 2
One possible answer is “cdcdcd” and the repeatingK length substring is “cd”. The minimum cost to required to convert the string is calcualted by the following steps:
Step 1: Replace S with “c”. Therefore, cost = |”a”-“c”| = 2.
Step 2: Replace S with “d”. Therefore, cost = |”b”-“d”| = 2.
Step 3: Replace S with “c”. Therefore, cost = |”c”-“c”| = 0.
Step 4: Replace S with “d”. Therefore, cost = |”d”-“d”| = 0.
Step 5: Replace S with “c”. Therefore, cost = |”e”-“c”| = 2.
Step 6: Replace S with “d”. Therefore, cost = |”f”-“d”| = 2.
Therefore, the minimum cost required = 2 + 2 + 0 + 0 + 2 + 2 = 8.
Input: S = “abcabc”, K = 3
The given string already consists a repeating substring “abc” of length K
Naive Approach: The simplest approach is to generate all possible permutations of length K and find the cost to convert the given string such that it has a repeating pattern of length K. Then, print the minimum cost among them.
Time Complexity: O(N*K26), where N is the length of the given string and K is the given integer.
Auxiliary Space: O(N)
Efficient Approach: The idea is to use a Greedy Technique and observe that for any position i from 0 to K – 1, characters at position i + j * K must be the same where 0 ≤ j < N/K. For example, if S = “abcbbc” and K = 3 then, characters at positions 0 and 3 must be equal, characters at positions 1 and 4 must the same, and characters at positions 2 and 5 must be equal. Therefore, the minimum cost for characters at positions i + j * K can be calcualted individually. Follow the steps below to solve the problem:
- Initialize a variable ans to store the minimum cost required.
- Traverse the string over the range [0, K – 1].
- For every position i, find the cost to place a character at positions i + j * K, for every character, where 0 ≤ j < N/K. Calcualte the minimum cost among them and update ans.
- After completing the above steps, print the value of ans as the required minimum cost.
Below is the implementation of the above approach:
Time Complexity: O(N + K)
Auxiliary Space: O(N)