Open In App

Minimum cost to make two strings identical by deleting the digits

Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings X and Y consisting of only digits ‘0’ to ‘9’. Find minimum cost required to make the given two strings identical. Only operation allowed is to delete characters from any of the string. The cost of operation of deleting the digit ‘d’ is d units. 

Input:  X = 3759, Y = 9350
Output: 23
Explanation
For making both string identical, delete
characters 3, 7, 5 from first string and
delete characters 3, 5, 0 from second 
string. Total cost of operation is
3 + 7 + 5 + 3 + 5 + 0 = 23

Input:  X = 3198, Y = 98
Output: 4

This problem is a variation of Longest Common Subsequence( LCS ) and this one. The idea is simple, instead of finding the length of longest common subsequence, find the maximum cost by adding identical characters from both the string.

Now to find the minimum cost, subtract the above result from total cost of both strings i.e., 

costX = Cost of removing all characters
        from string 'X'
CostY = Cost of removing all characters 
        from string 'Y'
cost_Id = Cost of removing identical characters
          from both strings

Minimum cost to make both string identical = 
                      costX + costY - cost_Id

Below is the implementation of above approach: 

C++




/* C++ code to find minimum cost to make two strings
   identical */
#include <bits/stdc++.h>
using namespace std;
 
/* Function to return cost of removing the identical
   characters in LCS for X[0..m-1], Y[0..n-1] */
int lcs(char* X, char* Y, int m, int n)
{
    int L[m + 1][n + 1];
 
    /* Following steps build L[m+1][n+1] in bottom
       up fashion. Note that L[i][j] contains cost
       of removing identical characters in LCS of
       X[0..i-1] and Y[0..j-1] */
    for (int i = 0; i <= m; ++i) {
        for (int j = 0; j <= n; j++) {
 
            if (i == 0 || j == 0)
                L[i][j] = 0;
 
            // If both characters are same, add both
            // of them
            else if (X[i - 1] == Y[j - 1])
                L[i][j] = L[i - 1][j - 1] +
                          2 * (X[i - 1] - '0');
 
            // Otherwise find the maximum cost among them
            else
                L[i][j] = max(L[i - 1][j], L[i][j - 1]);
        }
    }
 
    return L[m][n];
}
 
// Returns cost of making X[] and Y[] identical
int findMinCost(char X[], char Y[])
{
    // Find LCS of X[] and Y[]
    int m = strlen(X), n = strlen(Y);
 
    // Initialize the cost variable
    int cost = 0;
 
    // Find cost of all characters in
    // both strings
    for (int i = 0; i < m; ++i)
        cost += X[i] - '0';
 
    for (int i = 0; i < n; ++i)
        cost += Y[i] - '0';
 
    return cost - lcs(X, Y, m, n);
}
 
/* Driver program to test above function */
int main()
{
    char X[] = "3759";
    char Y[] = "9350";
    cout << "Minimum Cost to make two strings "
         << "identical is = " << findMinCost(X, Y);
    return 0;
}


Java




// Java code to find minimum cost to
// make two strings identical
import java.util.*;
import java.lang.*;
 
public class GfG{
     
/* Function to return cost of removing the identical
characters in LCS for X[0..m-1], Y[0..n-1] */
static int lcs(char[] X, char[] Y, int m, int n)
{
    int[][] L=new int[m + 1][n + 1];
 
    /* Following steps build L[m+1][n+1] in
    bottom up fashion. Note that L[i][j] contains
    cost of removing identical characters in
    LCS of X[0..i-1] and Y[0..j-1] */
    for (int i = 0; i <= m; ++i) {
        for (int j = 0; j <= n; j++) {
 
            if (i == 0 || j == 0)
                L[i][j] = 0;
 
            // If both characters are same,
            // add both of them
            else if (X[i - 1] == Y[j - 1])
                L[i][j] = L[i - 1][j - 1] +
                        2 * (X[i - 1] - '0');
 
            // Otherwise find the maximum
            // cost among them
            else
                L[i][j] = L[i - 1][j] > L[i][j - 1] ?
                          L[i - 1][j] : L[i][j - 1];
        }
    }
 
    return L[m][n];
}
 
// Returns cost of making X[] and Y[] identical
static int findMinCost(char X[], char Y[])
{
    // Find LCS of X[] and Y[]
    int m = X.length, n = Y.length;
 
    // Initialize the cost variable
    int cost = 0;
 
    // Find cost of all characters in
    // both strings
    for (int i = 0; i < m; ++i)
        cost += X[i] - '0';
 
    for (int i = 0; i < n; ++i)
        cost += Y[i] - '0';
 
    return cost - lcs(X, Y, m, n);
}
 
// driver function
    public static void main(String argc[]){
 
    char X[] = ("3759").toCharArray();
    char Y[] = ("9350").toCharArray();
     
    System.out.println("Minimum Cost to make two strings"+
                 " identical is = " +findMinCost(X, Y));
    }
}
 
// This code is contributed by Prerna Saini


Python3




# Python3 code to find minimum cost to make two strings
#   identical
 
# Function to return cost of removing the identical
# characters in LCS for X[0..m-1], Y[0..n-1]
def lcs(X, Y,  m,  n):
    L=[[0 for i in range(n+1)]for i in range(m+1)]
   
    # Following steps build L[m+1][n+1] in bottom
    # up fashion. Note that L[i][j] contains cost
    # of removing identical characters in LCS of
    # X[0..i-1] and Y[0..j-1]
    for i in range(m+1):
        for j in range(n+1):
            if (i == 0 or j == 0):
                L[i][j] = 0
   
            # If both characters are same, add both
            # of them
            elif (X[i - 1] == Y[j - 1]):
                L[i][j] = L[i - 1][j - 1] + 2 * (ord(X[i - 1]) - 48)
   
            # Otherwise find the maximum cost among them
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]
   
# Returns cost of making X[] and Y[] identical
def findMinCost( X,  Y):
    # Find LCS of X[] and Y[]
    m = len(X)
    n = len(Y)
    # Initialize the cost variable
    cost = 0
   
    # Find cost of all acters in
    # both strings
    for i in range(m):
        cost += ord(X[i]) - 48
   
    for i in range(n):
        cost += ord(Y[i]) - 48
    ans=cost - lcs(X, Y, m, n)
    return ans
   
# Driver program to test above function
X = "3759"
Y = "9350"
print("Minimum Cost to make two strings ",
     "identical is = " ,findMinCost(X, Y))
 
#this code is contributed by sahilshelangia


C#




// C# code to find minimum cost to
// make two strings identical
using System;
 
public class GfG{
     
    /* Function to return cost of removing the identical
    characters in LCS for X[0..m-1], Y[0..n-1] */
    static int lcs(string X, string Y, int m, int n)
    {
        int [,]L=new int[m + 1,n + 1];
     
        /* Following steps build L[m+1][n+1] in
        bottom up fashion. Note that L[i][j] contains
        cost of removing identical characters in
        LCS of X[0..i-1] and Y[0..j-1] */
        for (int i = 0; i <= m; ++i) {
            for (int j = 0; j <= n; j++) {
     
                if (i == 0 || j == 0)
                    L[i,j] = 0;
     
                // If both characters are same,
                // add both of them
                else if (X[i - 1] == Y[j - 1])
                    L[i,j] = L[i - 1,j - 1] +
                            2 * (X[i - 1] - '0');
     
                // Otherwise find the maximum
                // cost among them
                else
                    L[i,j] = L[i - 1,j] > L[i,j - 1] ?
                            L[i - 1,j] : L[i,j - 1];
            }
        }
     
        return L[m,n];
    }
     
    // Returns cost of making X[] and Y[] identical
    static int findMinCost( string X, string Y)
    {
        // Find LCS of X[] and Y[]
        int m = X.Length, n = Y.Length;
     
        // Initialize the cost variable
        int cost = 0;
     
        // Find cost of all characters in
        // both strings
        for (int i = 0; i < m; ++i)
            cost += X[i] - '0';
     
        for (int i = 0; i < n; ++i)
            cost += Y[i] - '0';
     
        return cost - lcs(X, Y, m, n);
    }
     
    // Driver function
    public static void Main()
    {
        string X = "3759";
        string Y= "9350";
         
        Console.WriteLine("Minimum Cost to make two strings"+
                    " identical is = " +findMinCost(X, Y));
    }
}
 
// This code is contributed by vt_m


PHP




<?php
// PHP code to find minimum cost to
// make two strings identical
 
/* Function to return cost of removing the identical
characters in LCS for X[0..m-1], Y[0..n-1] */
function lcs( $X, $Y, $m, $n)
{
    $L = array($m + 1,$n+ 1);
 
    /* Following steps build L[m+1][n+1] in
    bottom up fashion. Note that L[i][j] contains
    cost of removing identical characters in
    LCS of X[0..i-1] and Y[0..j-1] */
    for ($i = 0; $i <= $m; ++$i)
    {
        for ($j = 0; $j <= $n; $j++)
        {
 
            if ($i == 0 || $j == 0)
                $L[$i][$j] = 0;
 
            // If both characters are same,
            // add both of them
            else if ($X[$i - 1] == $Y[$j - 1])
                $L[$i][$j] = $L[$i - 1][$j - 1] +
                        2 * ($X[$i - 1] - '0');
 
            // Otherwise find the maximum
            // cost among them
            else
                $L[$i][$j] = $L[$i - 1][$j] > $L[$i][$j - 1] ?
                        $L[$i - 1][$j] : $L[$i][$j - 1];
        }
    }
 
    return $L[$m][$n];
}
 
// Returns cost of making X[] and Y[] identical
function findMinCost($X, $Y)
{
    // Find LCS of X[] and Y[]
    $m = sizeof($X); $n = sizeof($Y);
 
    // Initialize the cost variable
    $cost = 0;
 
    // Find cost of all characters in
    // both strings
    for ($i = 0; $i < $m; ++$i)
        $cost += $X[$i] - '0';
 
    for ($i = 0; $i < $n; ++$i)
        $cost += $Y[$i] - '0';
 
    return $cost - lcs($X, $Y, $m, $n);
}
 
// Driver code
 
    $X = str_split("3759");
    $Y = str_split("9350");
     
    echo("Minimum Cost to make two strings".
                " identical is = " .findMinCost($X, $Y));
     
// This code is contributed by Code_Mech.


Javascript




<script>
    // Javascript code to find minimum cost to make two strings identical
     
    /* Function to return cost of removing the identical
    characters in LCS for X[0..m-1], Y[0..n-1] */
    function lcs(X, Y, m, n)
    {
        let L=new Array(m + 1);
         
        for (let i = 0; i <= m; ++i)
        {
            L[i] = new Array(n + 1);
            for (let j = 0; j <= n; j++)
            {
                L[i][j] = 0;
            }
        }
 
        /* Following steps build L[m+1][n+1] in
        bottom up fashion. Note that L[i][j] contains
        cost of removing identical characters in
        LCS of X[0..i-1] and Y[0..j-1] */
        for (let i = 0; i <= m; ++i) {
            for (let j = 0; j <= n; j++) {
 
                if (i == 0 || j == 0)
                    L[i][j] = 0;
 
                // If both characters are same,
                // add both of them
                else if (X[i - 1] == Y[j - 1])
                    L[i][j] = L[i - 1][j - 1] +
                            2 * (X[i - 1] - '0');
 
                // Otherwise find the maximum
                // cost among them
                else
                    L[i][j] = L[i - 1][j] > L[i][j - 1] ?
                              L[i - 1][j] : L[i][j - 1];
            }
        }
 
        return L[m][n];
    }
 
    // Returns cost of making X[] and Y[] identical
    function findMinCost(X, Y)
    {
        // Find LCS of X[] and Y[]
        let m = X.length, n = Y.length;
 
        // Initialize the cost variable
        let cost = 0;
 
        // Find cost of all characters in
        // both strings
        for (let i = 0; i < m; ++i)
            cost += X[i].charCodeAt() - '0'.charCodeAt();
 
        for (let i = 0; i < n; ++i)
            cost += Y[i].charCodeAt() - '0'.charCodeAt();
 
        return cost - lcs(X, Y, m, n);
    }
     
    let X = ("3759").split('');
    let Y = ("9350").split('');
       
    document.write("Minimum Cost to make two strings"+
                 " identical is = " +findMinCost(X, Y));
     
</script>


Output

Minimum Cost to make two strings identical is = 23

Time complexity: O(m*n), As we are traversing the matrix of size m*n once.
Auxiliary space: O(m*n), Extra space is used to store the elements of the matrix.

Efficient approach: Space optimization

In previous approach the current value L[i][j] is only depend upon the current and previous row values of matrix. So to optimize the space complexity we use a single 1D array to store the computations.

Implementation steps:

  • Create a 1D vector L of size n+1 and initialize it with 0.
  • Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
  • Now Create variable prev used to store previous computations and curr to store the current value.
  • After every iteration assign the value of curr to prev for further iteration.
  • Initialize a variable cost to store the final answer and update it by iterating through the L.
  • At last return and print the final answer stored in cost.

Implementation:

C++




// C++ code to find minimum cost to
// make two strings identical
 
#include <bits/stdc++.h>
using namespace std;
 
 
// Returns cost of making X[] and Y[] identical
int findMinCost(char X[], char Y[]) {
    int m = strlen(X), n = strlen(Y);
     
    // vector to store computations
    vector<int> L(n + 1, 0);
     
    // iterate over subproblems
    for (int i = 0; i < m; ++i) {
        // to store previous element
        int prev = 0;
        for (int j = 0; j < n; j++) {
             
            // current element
            int curr = L[j+1];
             
            // update L
            if (X[i] == Y[j]) {
                L[j+1] = prev + 2 * (X[i] - '0');
            } else {
                L[j+1] = max(L[j], L[j+1]);
            }
             
            // assign value to iterate further
            prev = curr;
        }
    }
     
    // to store minimum cost
    int cost = 0;
    for (int i = 0; i < m; ++i) {
        cost += X[i] - '0';
    }
    for (int i = 0; i < n; ++i) {
        cost += Y[i] - '0';
    }
     
    // return final answer
    return cost - L[n];
}
 
// Driver code
int main() {
    char X[] = "3759";
    char Y[] = "9350";
     
    // function call
    cout << "Minimum Cost to make two strings "
         << "identical is = " << findMinCost(X, Y);
    return 0;
}


Java




// Java code to find minimum cost to
// make two strings identical
import java.lang.*;
import java.util.*;
 
class GfG {
 
  // Returns cost of making X[] and Y[] identical
  static int findMinCost(char X[], char Y[])
  {
    int m = X.length, n = Y.length;
 
    // vector to store computations
    int[] L = new int[n + 1];
 
    // iterate over subproblems
    for (int i = 0; i < m; ++i) {
      // to store previous element
      int prev = 0;
      for (int j = 0; j < n; j++) {
 
        // current element
        int curr = L[j + 1];
 
        // update L
        if (X[i] == Y[j]) {
          L[j + 1] = prev + 2 * (X[i] - '0');
        }
        else {
          L[j + 1] = Math.max(L[j], L[j + 1]);
        }
 
        // assign value to iterate further
        prev = curr;
      }
    }
 
    // to store minimum cost
    int cost = 0;
    for (int i = 0; i < m; ++i) {
      cost += X[i] - '0';
    }
    for (int i = 0; i < n; ++i) {
      cost += Y[i] - '0';
    }
 
    // return final answer
    return cost - L[n];
  }
  public static void main(String[] args)
  {
    char[] X = "3759".toCharArray();
    char[] Y = "9350".toCharArray();
 
    // function call
    System.out.println(
      "Minimum Cost to make two strings identical is = "
      + findMinCost(X, Y));
  }
}
 
// This code is contributed by Karandeep1234


Python




def find_min_cost(X, Y):
    m, n = len(X), len(Y)
 
    # list to store computations
    L = [0] * (n + 1)
 
    # iterate over subproblems
    for i in range(m):
        # to store previous element
        prev = 0
        for j in range(n):
            # current element
            curr = L[j+1]
 
            # update L
            if X[i] == Y[j]:
                L[j+1] = prev + 2 * int(X[i])
            else:
                L[j+1] = max(L[j], L[j+1])
 
            # assign value to iterate further
            prev = curr
 
    # to store minimum cost
    cost = sum(int(c) for c in X) + sum(int(c) for c in Y)
 
    # return final answer
    return cost - L[n]
 
# Driver code
X = "3759"
Y = "9350"
 
# function call
print("Minimum Cost to make two strings identical is = " + str(find_min_cost(X, Y)))


C#




using System;
using System.Collections.Generic;
 
class Program
{
 
  // Returns cost of making X[] and Y[] identical
  static int findMinCost(char[] X, char[] Y)
  {
    int m = X.Length, n = Y.Length;
 
    // vector to store computations
    List<int> L = new List<int>(n + 1);
    for (int i = 0; i < n + 1; i++) {
      L.Add(0);
    }
 
    // iterate over subproblems
    for (int i = 0; i < m; ++i) {
      // to store previous element
      int prev = 0;
      for (int j = 0; j < n; j++) {
 
        // current element
        int curr = L[j + 1];
 
        // update L
        if (X[i] == Y[j]) {
          L[j + 1] = prev + 2 * (X[i] - '0');
        }
        else {
          L[j + 1] = Math.Max(L[j], L[j + 1]);
        }
 
        // assign value to iterate further
        prev = curr;
      }
    }
 
    // to store minimum cost
    int cost = 0;
    for (int i = 0; i < m; ++i) {
      cost += X[i] - '0';
    }
    for (int i = 0; i < n; ++i) {
      cost += Y[i] - '0';
    }
 
    // return final answer
    return cost - L[n];
  }
 
  // Driver code
  static void Main(string[] args)
  {
    char[] X = "3759".ToCharArray();
    char[] Y = "9350".ToCharArray();
 
    // function call
    Console.WriteLine(
      "Minimum Cost to make two strings identical is = "
      + findMinCost(X, Y));
  }
}


Javascript




function findMinCost(X, Y) {
    const m = X.length;
    const n = Y.length;
 
    // list to store computations
    const L = new Array(n + 1).fill(0);
 
    // iterate over subproblems
    for (let i = 0; i < m; i++) {
        // to store previous element
        let prev = 0;
        for (let j = 0; j < n; j++) {
            // current element
            const curr = L[j+1];
 
            // update L
            if (X[i] === Y[j]) {
                L[j+1] = prev + 2 * parseInt(X[i]);
            } else {
                L[j+1] = Math.max(L[j], L[j+1]);
            }
 
            // assign value to iterate further
            prev = curr;
        }
    }
 
    // to store minimum cost
    let cost = X.split("").reduce((acc, c) =>
    acc + parseInt(c), 0) + Y.split("").reduce((acc, c) => acc + parseInt(c), 0);
 
    // return final answer
    return cost - L[n];
}
 
// Driver code
const X = "3759";
const Y = "9350";
 
// function call
console.log("Minimum Cost to make two strings identical is = "
+ findMinCost(X, Y));


Output

Minimum Cost to make two strings identical is = 23

Time complexity: O(m*n), As we are traversing the matrix of size m*n once.
Auxiliary space: O(n)



Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads