Open In App

Minimum number of increment operations required to make two Strings equal

Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings S1 and S2 of the same length containing characters ranging from ‘0’ to ‘9’, the task is to return the minimum number of operations required to make two strings equal by following the below operations:

  • Increment any two characters from the string by 1.
  • If it is not possible to make two strings equal with above condition then return -1.

Examples:

Input : S1 = “12”, S2 = “21”
Output : 1
Explanation: Operation 1: Increment first index of S1 and 
second index of S2, new S1 = “22”, S2 = “22”

Input : “123”, S2 = “015”
Output : 2
Explanation: Operation 1: Increment third index of S1 and 
first index of S2, new S1 = “124”, S2 = “115”
Operation 2: Increment third index of S1 and second index of S2.
New S1 = “125”, S2 = “125”

Input: S1 = “19”, S2 = “24”
Output: -1
Explanation: There is no such valid operation exists through which 
we can make two strings equal.

Approach: To solve the problem follow the below observations:

Observations:

We are incrementing 1 to both the characters of strings to perform valid operation. So, if initially S1 and S2 have different sums, they can never be made equal (since they must have the same sum when they are equal). Now let, Sum(S1) = Sum(S2). Lets see for a specific index  
0 ? i ? N – 1(N is length of either string S1 or S2).

  • If S1[ i ] == s2[ i ], no operation will be needed
  • If s1[ i ] > S2[ i ], then we need to add S1[ i ] – S2[ i ] in S2 to make S1[ i ] and S2[ i ] equal.
  • If S1[ i ] < S2[ i ], then we need to add S2[ i ] – S1[ i ] in S1 to make S1[ i ] and S2[ i ] equal.

Let x is summation of S1[ i ] – S2[ i ] for all indices where S1[ i ] > S2[ i ]. As noted above, x is the minimum number of operations we need to perform on indices of S2.

Let y is summation of S2[ i ] – S1[ i ] for all indices where S1[ i ] < S2[ i ]. As noted above, y is the minimum number of operations we need to perform on indices of S1.

We will find the total summation of operations needed on both the strings i.e (x+y) and we will divide it by 2 because in every single operation we need to increase any character from both the strings.

Below is the implementation of the above approach.

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to determine minimum number
// of increment operations
int minimum_operations(string S1, string S2)
{
    // To store sum of all digits
    // in S1 and S2
    int sum1 = 0, sum2 = 0;
 
    // Traversing on string and
    // finding sum of both strings
    for (int i = 0; i < S1.size(); i++) {
        sum1 += (S1[i] - '0');
        sum2 += (S2[i] - '0');
    }
 
    // If sum1 != sum2 they can
    // never be equal, then return -1
    if (sum1 != sum2)
        return -1;
 
    // To find count of valid operations
    int count = 0;
    for (int i = 0; i < S1.size(); i++) {
        if (S1[i] > S2[i]) {
 
            // Operations on S2 to make
            // S1 and S2 equal
            count += (S1[i] - S2[i]);
        }
        else {
            // Operations on S1 to make
            // S1 and S2 equal
            count += (S2[i] - S1[i]);
        }
    }
 
    return count / 2;
}
 
// Driver code
int main()
{
    string S1 = "123";
    string S2 = "015";
 
    // Function call
    cout << minimum_operations(S1, S2);
 
    return 0;
}


Java




// Java code for the above approach:
import java.io.*;
 
class GFG
{
   
  // Function to determine minimum number
  // of increment operations
  public static int minimum_operations(String S1,
                                       String S2)
  {
     
    // To store sum of all digits
    // in S1 and S2
    int sum1 = 0, sum2 = 0;
 
    // Traversing on string and
    // finding sum of both strings
    for (int i = 0; i < S1.length(); i++) {
      sum1 += (S1.charAt(i) - '0');
      sum2 += (S2.charAt(i) - '0');
    }
 
    // If sum1 != sum2 they can
    // never be equal, then return -1
    if (sum1 != sum2)
      return -1;
 
    // To find count of valid operations
    int count = 0;
    for (int i = 0; i < S1.length(); i++) {
      if (S1.charAt(i) > S2.charAt(i)) {
 
        // Operations on S2 to make
        // S1 and S2 equal
        count += (S1.charAt(i) - S2.charAt(i));
      }
      else {
        // Operations on S1 to make
        // S1 and S2 equal
        count += (S2.charAt(i) - S1.charAt(i));
      }
    }
 
    return count / 2;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S1 = "123";
    String S2 = "015";
 
    // Function call
    System.out.print(minimum_operations(S1, S2));
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python3 implementation of the approach
 
# Function to determine minimum number
# of increment operations
def minimum_operations(S1, S2) :
    # To store sum of all digits
    # in S1 and S2
    sum1 = 0
    sum2 = 0
 
    # Traversing on string and
    # finding sum of both strings
    for i in range(len(S1)):
        sum1 += (ord(S1[i]) - ord('0'))
        sum2 += (ord(S2[i]) - ord('0'))
     
 
    # If sum1 != sum2 they can
    # never be equal, then return -1
    if (sum1 != sum2) :
        return -1
 
    # To find count of valid operations
    count = 0
    for i in range(len(S1)):
        if (S1[i] > S2[i]) :
 
            # Operations on S2 to make
            # S1 and S2 equal
            count += (ord(S1[i]) - ord(S2[i]))
         
        else :
            # Operations on S1 to make
            # S1 and S2 equal
            count += (ord(S2[i]) - ord(S1[i]))
         
    return count // 2
 
# Driver code
if __name__ == "__main__":
     
    S1 = "123"
    S2 = "015"
 
    # Function call
    print(minimum_operations(S1, S2))
 
    # This code is contributed by sanjoy_62.


C#




// C# code for the above approach:
using System;
 
public class GFG {
 
  // Function to determine minimum number
  // of increment operations
  public static int minimum_operations(String S1,
                                       String S2)
  {
    // To store sum of all digits
    // in S1 and S2
    int sum1 = 0, sum2 = 0;
 
    // Traversing on string and
    // finding sum of both strings
    for (int i = 0; i < S1.Length; i++) {
      sum1 += (S1[i] - '0');
      sum2 += (S2[i] - '0');
    }
 
    // If sum1 != sum2 they can
    // never be equal, then return -1
    if (sum1 != sum2)
      return -1;
 
    // To find count of valid operations
    int count = 0;
    for (int i = 0; i < S1.Length; i++) {
      if (S1[i] > S2[i]) {
        // Operations on S2 to make
        // S1 and S2 equal
        count += (S1[i] - S2[i]);
      }
      else {
        // Operations on S1 to make
        // S1 and S2 equal
        count += (S2[i] - S1[i]);
      }
    }
 
    return count / 2;
  }
 
  static public void Main()
  {
 
    // Code
    String S1 = "123";
    String S2 = "015";
 
    // Function call
    Console.Write(minimum_operations(S1, S2));
  }
}
 
// This code is contributed by lokeshmvs21.


Javascript




<script>
    // JavaScript code for the above approach:
 
    // Function to determine minimum number
    // of increment operations
    const minimum_operations = (S1, S2) => {
        // To store sum of all digits
        // in S1 and S2
        let sum1 = 0, sum2 = 0;
 
        // Traversing on let and
        // finding sum of both strings
        for (let i = 0; i < S1.length; i++) {
            sum1 += (S1.charCodeAt(i) - '0'.charCodeAt(0));
            sum2 += (S2.charCodeAt(i) - '0'.charCodeAt(0));
        }
 
        // If sum1 != sum2 they can
        // never be equal, then return -1
        if (sum1 != sum2)
            return -1;
 
        // To find count of valid operations
        let count = 0;
        for (let i = 0; i < S1.length; i++) {
            if (S1[i] > S2[i]) {
 
                // Operations on S2 to make
                // S1 and S2 equal
                count += (S1.charCodeAt(i) - S2.charCodeAt(i));
 
            }
            else {
                // Operations on S1 to make
                // S1 and S2 equal
                count += (S2.charCodeAt(i) - S1.charCodeAt(i));
            }
        }
 
        return parseInt(count / 2);
    }
 
    // Driver code
 
    let S1 = "123";
    let S2 = "015";
 
    // Function call
    document.write(minimum_operations(S1, S2));
 
    // This code is contributed by rakeshsahni
 
</script>


Output

2

Time Complexity: O( N ), where N is the length of either string S1 or S2
Auxiliary Space: O( 1 )



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