Skip to content
Related Articles

Related Articles

Improve Article
Minimize cost to convert given string into concatenation of equal substrings of length K
  • Difficulty Level : Hard
  • Last Updated : 20 May, 2021

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 the same K-length substrings by performing the following operations:

  • A character can be replaced with another character.
  • The cost of each operation is the absolute difference between the replaced and the replaced character. For example, if ‘a’ is replaced with ‘z’, then the cost of the operation is |”a”-“z”| = 25.

Examples:

Input: S = “abcdef”, K = 2
Output: 8
Explanation:
One possible answer is “cdcdcd” and the repeated k length substring is “cd”. The minimum cost required to convert the string is calculated 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 calculated 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. Calculate 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:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum cost
// to convert given String into
// String of K length same subString
void minCost(string s, int k)
{
     
    // Stores length of String
    int n = s.size();
     
    // 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[26];
         
        for(int p = 0; p < 26; p++)
        {
            a[p] = 0;
        }
 
        for(int j = i; j < n; j += k)
        {
            a[s[j] - 'a']++;
        }
 
        // Stores minimum cost for
        // sequence of S[i]%k indices
        int min_cost = INT_MAX;
 
        // Check for optimal character
        for(int ch = 0; ch < 26; ch++)
        {
            int cost = 0;
 
            // Find sum of distance 'a'+ ch
            // from character S[i]%k indices
            for(int tr = 0; tr < 26; tr++)
                cost += abs(ch - tr) * a[tr];
 
            // Choose minimum cost for
            // each index i
            min_cost = min(min_cost, cost);
        }
         
        // Increment ans
        ans += min_cost;
    }
 
    // Print minimum cost to
    // convert String
    cout << (ans);
}
 
// Driver Code
int main()
{
     
    // Given String S
    string S = "abcdefabc";
 
    int K = 3;
 
    // Function Call
    minCost(S, K);
}
 
// This code is contributed by gauravrajput1

Java




// 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 character
            for (int ch = 0; ch < 26; ch++) {
 
                int cost = 0;
 
                // Find sum of distance 'a'+ ch
                // from character 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);
    }
}

Python3




# Python3 program for the
# above approach
import sys
 
# Function to find minimum cost
# to convert given string into
# string of K length same substring
def minCost(s, k):
      
    # Stores length of string
    n = len(s)
  
    # Stores the minimum cost
    ans = 0
  
    # Traverse left substring
    # of k length
    for i in range(k):
          
        # Stores the frequency
        a = [0] * 26
  
        for j in range(i, n, k):
            a[ord(s[j]) - ord('a')] += 1
         
        # Stores minimum cost for
        # sequence of S[i]%k indices
        min_cost = sys.maxsize - 1
  
        # Check for optimal character
        for ch in range(26):
            cost = 0
              
            # Find sum of distance 'a'+ ch
            # from character S[i]%k indices
            for tr in range(26):
                cost += abs(ch - tr) * a[tr]
  
            # Choose minimum cost for
            # each index i
            min_cost = min(min_cost,
                               cost)
                                
        # Increment ans
        ans += min_cost
     
    # Print minimum cost to
    # convert string
    print(ans)
 
# Driver Code
      
# Given string S
S = "abcdefabc"
  
K = 3
  
# Function call
minCost(S, K)
 
# This code is contributed by code_hunt

C#




// C# program for the
// above approach
using System;
 
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[j] - 'a']++;
        }
 
        // Stores minimum cost for
        // sequence of S[i]%k indices
        int min_cost = Int32.MaxValue;
 
        // Check for optimal character
        for(int ch = 0; ch < 26; ch++)
        {
            int cost = 0;
             
            // Find sum of distance 'a'+ ch
            // from character 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
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
     
    // Given string S
    string S = "abcdefabc";
 
    int K = 3;
 
    // Function call
    minCost(S, K);
}
}
 
// This code is contributed by sanjoy_62

Javascript




<script>
// Javascript program for the above approach
 
// Function to find minimum cost
// to convert given String into
// String of K length same subString
function minCost(s, k)
{
     
    // Stores length of String
    var n = s.length;
     
    // Stores the minimum cost
    var ans = 0;
 
    // Traverse left subString
    // of k length
    for(var i = 0; i < k; i++)
    {
         
        // Stores the frequency
        var a = new Array(26).fill(0);
 
        for(var j = i; j < n; j += k)
        {
            a[s[j].charCodeAt(0) - 'a'.charCodeAt(0)]++;
        }
 
        // Stores minimum cost for
        // sequence of S[i]%k indices
        var min_cost = 1000000000;
 
        // Check for optimal character
        for(var ch = 0; ch < 26; ch++)
        {
            var cost = 0;
 
            // Find sum of distance 'a'+ ch
            // from character S[i]%k indices
            for(var 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
    document.write(ans);
}
 
// Driver Code
// Given String S
var S = "abcdefabc";
var K = 3;
// Function Call
minCost(S, K);
 
</script>
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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :