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.
Input: A = “1aB+-“, B = “CC”
Explanation: Remove all 5 characters from string A and insert character C twice. Therefore, the total cost = 5 + 2 = 7.
Input: A = “aBcD”, B = “DBac”
Explanation: 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:
Time Complexity: O(N + M)
Auxiliary Space: O(N + M)
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 Geeks Classes Live