Minimum Cost to Modify a String


Introduction

In this tutorial, we use C++ programming concepts to implement examples to find the minimum cost to modify a string. String modification includes operations to change one string into another string. String operations include insertion, deletion, and substitution. We predefined the cost of each operation. You can choose the cost values of your choice. Generate output by calculating the total operation cost for string modification.

The insertion function is used to insert missing characters, deletion is used to remove unwanted characters, and the substitution operation is used to replace a character with another character.

For implementing the above task we use two logic:

  • Dynamic Programming: Dividing a program into sub-parts reduces time and complexity.

  • Recursive Function Call: Calling a function repeatedly until the task is complete.

Demonstration 1

String1 = “book”
String2 = “back”
costInsertion = 1
costDeletion = 1
costSubstitution = 2

Output

4

In the above demonstration, string1 is modified to string2 using 3 different operations (costInsertion, costDeletion, costSubstitution) ; these operations define the cost of using each one. To insert a new element, it takes a cost of 1. The cost of deleting an already existing element is 1 and the cost of substituting an element with a new element is 2. Each operation costs predefined amounts. Using the operation the cost of converting string1 to string2 is 2 which includes substituting “o” with “a” and “o” with “c”.

Demonstration 2

String1 = “abcdef”
String2 = “azced”
costInsertion = 1
costDeletion = 1
costSubstitution = 1

Output

Minimum string modification cost is 5

In the above demonstration, string1 is modified to string2 using 3 operations: insertion, deletion, and substitution. Each operation costs are predefined. To convert string1 into string2 the total cost is 5, which includes operations like deleting “b”, “d”, and “f”, inserting “z” and “d” .

C++ Library Functions Used in Examples

Syntax

length() : This built-in library function is defined in the <string> header file. It returns the string length in the form of the total number of characters.

string_name.length();

vector() : It is defined in the header file. It is a dynamic array with easy insertion and deletion operations.

vector<data_type> vector_name;

Algorithm

  • Take two input strings.

  • Define the cost of each operation.

  • Create a 2D array of (m+1)x (n+1), where m is the length of the first string and n is the length of the second string.

  • Iterate over each character of the input string to check the need for particular operations and perform operations as per string2 requirements.

  • Return the total minimum cost of string modification operations.

Example 1

We implemented a demonstration using recursion. The minimumCost() function calculates the minimum cost to modify string1 to string2. The function considers 3 cases: when one of the strings is empty, use an insertion/deletion operation, returning the minimum among them.

#include <iostream>
#include <algorithm>
using namespace std;

int minimumCost(string str1, string str2, int insertionCost, int deletionCost, int substitutionCost, int x, int y) 
{

    if (x == 0) 
    {
        return y * insertionCost;
    }
    if (y == 0) 
    {
        return x * deletionCost;
    }

    if (str1[x - 1] == str2[y - 1])
    {
        return minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost, x - 1, y - 1);
    }

    // Recursively calculating the operation cost 
    int cd = deletionCost + minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost, x - 1,
    y);
    int ci = insertionCost + minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost, x, y - 1);
    int cs = substitutionCost + minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost, x - 1, y - 1);

    return min({cd, ci, cs});
}

int main() {
    string str1 = "kitten";
    string str2 = "sitting";
    int insertionCost = 1;
    int deletionCost = 1;
    int substitutionCost = 2;

    int m = minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost, str1.length(), str2.length());

    cout << "Minimum cost to modify the string: " << m << endl;

    return 0;
}

Output

Minimum cost to modify the string : 5

Example 2

We implement one of the demonstrations using dynamic programming. The recursive approach is time complex and is not useful for large inputs. Dynamic programming is efficient as it divides a problem into chunks.

Created a minimumCost() function and array dp to iterate over each character of the string. Used length() function to find the length of input strings.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
//user-defined function to calculate the minimum cost
int minimumCost(string str1, string str2, int insertionCost, int deletionCost, int substitutionCost) 
{
    int a = str1.length();
    int b = str2.length();

    vector<vector<int>> dp(a + 1, vector<int>(b + 1, 0));
    for (int x = 0; x <= a; x++) 
    {
        dp[x][0] = x * deletionCost;
    }
    for (int y = 0; y <= b; y++) 
    {
        dp[0][y] = y * insertionCost;
    }


    for (int x = 1; x <= a; x++) 
    {
        for (int y = 1; y <= b; y++) 
        {
            if (str1[x - 1] == str2[y - 1]) 
            {
                dp[x][y] = dp[x - 1][y - 1];
            } 
            else 
            {
                dp[x][y] = min({dp[x - 1][y] + deletionCost,
                                dp[x][y - 1] + insertionCost,
                                dp[x - 1][y - 1] + substitutionCost});
            }
        }
    }

    // Return the minimum cost in array form
    return dp[a][b];
}

int main() 
{
    string str1 = "kitten";
    string str2 = "sitting";
    int insertionCost = 1;
    int deletionCost = 1;
    int substitutionCost = 2;

    int mc = minimumCost(str1, str2, insertionCost, deletionCost, substitutionCost);

    cout << "Minimum cost to modify the string: " << mc << endl;

    return 0;
}

Output

Minimum cost to modify the string. 5 

Conclusion

We reached the end of this tutorial, we implemented two examples using dynamic programming and a recursive approach. To modify the string three different operations: insertion, deletion, and substitution are used. The cost of each operation is predefined in the examples.

Updated on: 18-Aug-2023

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements