Minimum cost to convert one given string to another using swap, insert or delete operations Last Updated : 11 Nov, 2022 Comments Improve Suggest changes Like Article Like Report Given two strings A and B of length N and M respectively, the task is to find the minimum cost to convert string A to B using the following operations: A character of string A can be swapped from another character of the same string. Cost = 0.A character can be deleted from string B or can be inserted in the string A. Cost = 1. Examples: Input: A = "1aB+-", B = "CC"Output: 7Explanation: Remove all 5 characters from string A and insert character C twice. Therefore, the total cost = 5 + 2 = 7. Input: A = "aBcD", B = "DBac"Output: 0Explanation: Following operations need to be performed to convert string A to string B: Swap 'a' with 'D'. Therefore, A = "DBca".Swap 'a' with 'c'. Therefore, A = "DBac". Therefore, the total cost = 0. Approach: The idea is to perform a swap operation maximum number of times to reduce the total cost. Observe that the characters which are common between the strings A and B can be swapped any number of times in A to make the string equal to B. All the characters that are present in the string A but not in the string B have to be deleted from A and all the characters present in B and not present in A have to be inserted in A to make both the strings equal. Follow the steps below to solve the problem: Initialize two arrays a[] and b[] of length 256 to store the frequencies of each character in the strings A and B respectively.Initialize a variable, say minCost, to store the minimum cost.Traverse over the range [0, 255] using the variable i and at each iteration, increment minCost by abs(a[i] - b[i]).After completing the above steps, print the value of minCost as the minimum cost required to convert string A to B. 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 the minimum cost // to convert string a to b void minimumCost(string a, string b) { // Stores the frequency of string // a and b respectively vector<int> fre1(256), fre2(256); // Store the frequencies of // characters in a for (char c : a) fre1[(int)(c)]++; // Store the frequencies of // characters in b for (char c : b) fre2[(int)(c)]++; // Minimum cost to convert A to B int mincost = 0; // Find the minimum cost for (int i = 0; i < 256; i++) { mincost += abs(fre1[i] - fre2[i]); } // Print the minimum cost cout << mincost << endl; } // Driver Code int main() { string A = "1AB+-", B = "cc"; // Function Call minimumCost(A, B); return 0; } Java // Java program for the above approach import java.util.*; class GFG{ // Function to find the minimum cost // to convert string a to b public static void minimumCost(String a, String b) { // Stores the frequency of string // a and b respectively int fre1[] = new int[256]; int fre2[] = new int[256]; // Store the frequencies of // characters in a for(char c : a.toCharArray()) fre1[(int)(c)]++; // Store the frequencies of // characters in b for(char c : b.toCharArray()) fre2[(int)(c)]++; // Minimum cost to convert A to B int mincost = 0; // Find the minimum cost for(int i = 0; i < 256; i++) { mincost += Math.abs(fre1[i] - fre2[i]); } // Print the minimum cost System.out.println(mincost); } // Driver Code public static void main(String[] args) { String A = "1AB+-", B = "cc"; // Function Call minimumCost(A, B); } } // This code is contributed by divyeshrabadiya07 Python3 # Python3 program for the above approach # Function to find the minimum cost # to convert a to b def minimumCost(a, b): # Stores the frequency of string # a and b respectively fre1 = [0]*(256) fre2 = [0]*(256) # Store the frequencies of # characters in a for c in a: fre1[ord(c)] += 1 # Store the frequencies of # characters in b for c in b: fre2[ord(c)] += 1 # Minimum cost to convert A to B mincost = 0 # Find the minimum cost for i in range(256): mincost += abs(fre1[i] - fre2[i]) # Print the minimum cost print(mincost) # Driver Code if __name__ == '__main__': A = "1AB+-" B = "cc" # Function Call minimumCost(A, B) # This code is contributed by mohit kumar 29 C# // C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to find the minimum cost // to convert string a to b public static void minimumCost(string a, string b) { // Stores the frequency of string // a and b respectively int[] fre1 = new int[256]; int[] fre2 = new int[256]; // Store the frequencies of // characters in a foreach(char c in a.ToCharArray()) fre1[(int)(c)]++; // Store the frequencies of // characters in b foreach(char c in b.ToCharArray()) fre2[(int)(c)]++; // Minimum cost to convert A to B int mincost = 0; // Find the minimum cost for(int i = 0; i < 256; i++) { mincost += Math.Abs(fre1[i] - fre2[i]); } // Print the minimum cost Console.Write(mincost); } // Driver code public static void Main() { string A = "1AB+-", B = "cc"; // Function Call minimumCost(A, B); } } // This code is contributed by sanjoy_62 JavaScript <script> // Javascript program for the above approach // Function to find the minimum cost // to convert string a to b function minimumCost(a, b) { // Stores the frequency of string // a and b respectively var fre1 = Array(256).fill(0), fre2= Array(256).fill(0); // Store the frequencies of // characters in a a.split('').forEach(c => { fre1[c.charCodeAt(0)]++; }); // Store the frequencies of // characters in b b.split('').forEach(c => { fre2[c.charCodeAt(0)]++; }); // Minimum cost to convert A to B var mincost = 0; // Find the minimum cost for (var i = 0; i < 256; i++) { mincost += Math.abs(fre1[i] - fre2[i]); } // Print the minimum cost document.write( mincost ); } // Driver Code var A = "1AB+-", B = "cc"; // Function Call minimumCost(A, B); // This code is contributed by importantly. </script> Output: 7 Time Complexity: O(N + M)Auxiliary Space: O(1) because constant size arrays fre1 and fre2 are used Comment More infoAdvertise with us Next Article Minimum cost to convert one given string to another using swap, insert or delete operations G grand_master Follow Improve Article Tags : Strings Greedy Hash DSA cpp-vector frequency-counting +2 More Practice Tags : GreedyHashStrings Similar Reads Minimum number of given operations required to convert a string to another string Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice 14 min read Converting one string to other using append and delete last operations Given an integer k and two strings str1 and str2 determine whether or not we can convert str1 to str2 by performing exactly k of the below operations on str1. Append a lowercase English alphabetic letter to the end of the str1. Delete the last character in str1 (Performing this operation on an empty 7 min read Check if one string can be converted to other using given operation Given two strings S and T of same length. The task is to determine whether or not we can build a string A(initially empty) equal to string T by performing the below operations. Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A. 15+ min read Minimum cost to convert str1 to str2 with the given operations Given two strings of equal lengths str1 and str2 consist of characters 'a' and 'b' only. The following operations can be performed on str1: Any character can be changed from 'a' to 'b' or from 'b' to 'a' with 1 unit cost.Any two characters str1[i] and str1[j] can be swapped with cost |i - j|. The ta 6 min read Minimum operations to transform given string to another by moving characters to front or end Given two Strings S and T of length N consisting of lowercase alphabets, which are permutations of each other, the task is to print the minimum number of operations to convert S to T. In one operation, pick any character of the string S and move it either to the start or end of the string S. Example 13 min read Transform One String to Another using Minimum Number of Given Operation Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it's possible to convert the string. If yes, then output minimum no. of operations required for transformation.Examples: Input: A = "ABD", B 15+ min read Minimum swaps required to convert one binary string to another Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M. Examples: Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000 5 min read Convert given Binary String to another in minimum operations by flipping all bits except any 1 Given two binary strings s1 and s2, the task is to count the minimum operations to convert string s1 to s2. In one operation a set bit can be chosen and all other bits except that is flipped. If it is not possible to convert s1-> s2 print -1. Examples: Input: s1 = "100010111" s2 = "101101100"Outp 12 min read Minimum number of adjacent swaps to convert a string into its given anagram Given two strings s1 and s2, the task is to find the minimum number of steps required to convert s1 into s2. The only operation allowed is to swap adjacent elements in the first string. Every swap is counted as a single step.Examples: Input: s1 = "abcd", s2 = "cdab" Output: 4 Swap 2nd and 3rd elemen 8 min read 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 the same K-length substrings by performing the following operations: A character can be replaced with another 8 min read Like