Minimize cost to convert given string into concatenation of equal substrings of length K

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.

Examples:

Input: S = “abcdef”, K = 2
Output: 8
Explanation:
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[0] with “c”. Therefore, cost = |”a”-“c”| = 2.
Step 2: Replace S[1] with “d”. Therefore, cost = |”b”-“d”| = 2.
Step 3: Replace S[2] with “c”. Therefore, cost = |”c”-“c”| = 0.
Step 4: Replace S[3] with “d”. Therefore, cost = |”d”-“d”| = 0.
Step 5: Replace S[4] with “c”. Therefore, cost = |”e”-“c”| = 2.
Step 6: Replace S[5] with “d”. Therefore, cost = |”f”-“d”| = 2.
Therefore, the minimum cost required = 2 + 2 + 0 + 0 + 2 + 2 = 8.

Input: S = “abcabc”, K = 3
Output: 0
Explanation:
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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
  
import java.util.*;
import java.lang.*;
  
class GFG {
  
    // Function to find minimum cost
    // to convert given string into
    // string of K length same substring
    static void minCost(String s, int k)
    {
        // Stores length of string
        int n = s.length();
  
        // Stores the minimum cost
        int ans = 0;
  
        // Traverse left substring
        // of k length
        for (int i = 0; i < k; i++) {
  
            // Stores the frequency
            int[] a = new int[26];
  
            for (int j = i; j < n; j += k) {
                a[s.charAt(j) - 'a']++;
            }
  
            // Stores minimum cost for
            // sequence of S[i]%k indices
            int min_cost
                = Integer.MAX_VALUE;
  
            // Check for optimal charcter
            for (int ch = 0; ch < 26; ch++) {
  
                int cost = 0;
  
                // Find sum of distance 'a'+ ch
                // from charcter S[i]%k indices
                for (int tr = 0; tr < 26; tr++)
                    cost += Math.abs(ch - tr)
                            * a[tr];
  
                // Choose minimum cost for
                // each index i
                min_cost = Math.min(min_cost,
                                    cost);
            }
  
            // Increment ans
            ans += min_cost;
        }
  
        // Print minimum cost to
        // convert string
        System.out.println(ans);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given string S
        String S = "abcdefabc";
  
        int K = 3;
  
        // Function Call
        minCost(S, K);
    }
}

chevron_right


Output:

9

Time Complexity: O(N + K)
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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.