Minimize cost to convert given string into concatenation of equal substrings of length K
Last Updated :
19 Apr, 2024
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>
Time Complexity: O(N*K)
Auxiliary Space: O(1)
Similar Reads
Minimum flips required to convert given string into concatenation of equal substrings of length K
Given a binary string S and an integer K, the task is to find the minimum number of flips required to convert the given string into a concatenation of K-length equal sub-strings. It is given that the given string can be split into K-length substrings. Examples: Input: S = "101100101", K = 3 Output:
5 min read
Split a given string into substrings of length K with equal sum of ASCII values
Given a string str of size N and an integer K, the task is to check if the input string can be partitioned into substrings of size K having a constant sum of ASCII values.Examples: Input: str = "abdcbbdba" K = 3 Output: YES Explanation: 3 length substrings {"and", "cbb", "dba"} with sum of their ASC
6 min read
Minimum cost for constructing the subsequence of length K from given string S
Given a string S consisting of N lowercase English alphabets, and an integer K and, an array cost[] of size 26 denoting the cost of each lowercase English alphabet, the task is to find the minimum cost to construct a subsequence of length K from the characters of the string S. Examples: Input: S = "
11 min read
Minimize length of Substrings containing at least one common Character
Given a string str, the task is to find the minimum length of substrings such that all the sub strings of that length from str contains at least one common character. If no such length can be obtained, print -1. Example: Input: str = "saad" Output: 2 Explanation: All the substrings of length two of
10 min read
Minimize insertions required to make all characters of a given string equal
Given a binary string S of length N, the task is to find the minimum number of characters required to be inserted such that all the characters in the string becomes the same based on the condition that: If '1' is inserted into the string, then all the '0's nearest to the inserted '1' is flipped or v
5 min read
Minimize length of string by replacing K pairs of distinct adjacent characters
Given string str of length N, the task is to find the minimum length to which the given string can be reduced by replacing any pair of non-equal adjacent characters with a single character at most K times. Examples: Input: str = "aabc", K =1Output: 3Explanation: Replace "bc" with a single character
5 min read
Number of ways of choosing K equal substrings of any length for every query
Given a string str and Q queries. Each query consists of an integer K. The task is to find the number of ways of choosing K equal sub-strings of any length possible for every query. Note that the set of K substrings must be unique.Examples: Input: str = "aabaab", que[] = {3} Output: 4 "a" is the onl
9 min read
Count subsequences 01 in string generated by concatenation of given numeric string K times
Given a string S and a positive integer K, the task is to find the number of subsequences "01" in the string generated by concatenation of the given numeric string S K times. Examples: Input: S = "0171", K = 2Output: 6Explanation:The string formed by concatenation of S, K number of times is "0171017
6 min read
Minimize flips to make substrings of size K same and alternative
Given a binary string S of length N, the task is to minimize the count of operations required to find a binary string T of the same length N such that: In one operation, it is allowed to flip any bit, i.e. convert 0 to 1 or vice versa.In the binary string T, choose a number K, such that: N is perfec
9 min read
Longest substring of 0s in a string formed by k concatenations
Given a binary string of length n and an integer k. Consider another string T which is formed by concatenating the given binary string k times. The task is to print the maximum size of a substring of T containing only zeroes. Examples: Input: str = 110010, k = 3 Output: 2 str = 110010 T = 1100101100
8 min read