Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize operations to make one string contain only characters from other string

  • Last Updated : 12 Jan, 2022

Given two strings S1 and S2 containing only lower case English alphabets, the task is to minimize the number of operations required to make S1 contain only characters from S2 where in each operation any character of S1 can be converted to any other letter and the cost of the operation will be difference between those two letters.

Examples:

Input: S1 = “abc”, S2 = “ad”
Output: 2
Explanation:
The first character of S1 doesn’t required to change, as character ‘a’ also present in S2.
The second character of S1 can be changed to ‘a’ as to make it ‘a’ needs 1 operation and to make it to ‘d’ needs 2 operations.
The third character of S1 can be changed to ‘d’ as to make it ‘a’ needs 2 operations and to make it to ‘d’ needs 1 operation.
So the minimum number of operations to make the string “abc” to “aad” it needs 2 operations.

Input: S1 = “aaa”, S2 = “a”
Output: 0
Explanation: S1 contains characters only present in S2.

 

Approach: The idea is to find the minimum number of operations required to make each character of S1 to any of the characters of S2 which is nearest to that. Follow the below steps to solve the problem:

  • Initialize a variable, say minOpr as 0 that stores the minimum number of operations required.
  • Iterate over the range [0, N1) using the variable i and perform the following steps:
    • Check if the character S1[i] is present in the S2. If not present then continue with the iteration.
    • Iterate over the range [0, 26) using the variable j.
      • Check if S1[i] greater than S2[j] then find minimum of curMinOpr, (S1[i] – S2[j]) and (26 – (S1[i]-‘a’) + (S2[j] – ‘a’)) and store the value in curMinOpr.
      • Else, find minimum of curMinOpr, (S2[j] – S1[i]) and ((S1[i] – ‘a’) + (26 – (S2[j] – ‘a’))) and store the value in curMinOpr.
    • Update the value of minOpr to minOpr += curMinOpr.
  • Finally, print the value of minOpr.

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 number of
// operations required to make string S1
// contains only characters from the string S2
void minOperations(string S1, string S2,
                   int N1, int N2)
{
    // Stores the minimum of operations
    // required
    int minOpr = 0;
 
    for (int i = 0; i < N1; i++) {
 
        // Check character S1[i] is not
        // present in S2
        if (S2.find(S1[i]) != string::npos) {
            continue;
        }
 
        // Stores the minimum operations required
        // for the current character S1[i]
        int curMinOpr = INT_MAX;
 
        for (int j = 0; j < N2; j++) {
 
            // Check S1[i] alphabet is greater
            // than the S2[j] alphabet
            if (S1[i] > S2[j]) {
 
                // Find the minimum operations
                // required to make the
                // character S1[i] to S2[j]
                curMinOpr
                    = min(curMinOpr,
                          (min(S1[i] - S2[j],
                               26 - (S1[i] - 'a')
                                   + (S2[j] - 'a'))));
            }
            else {
 
                // Find the minimum operations
                // required to make the
                // character S1[i] to S2[j]
                curMinOpr = min(
                    curMinOpr,
                    (min(S2[j] - S1[i],
                         (S1[i] - 'a')
                             + (26 - (S2[j] - 'a')))));
            }
        }
 
        // Update the value of minOpr
        minOpr += curMinOpr;
    }
 
    // Print the value of minOpr
    cout << minOpr << endl;
}
 
// Driver code
int main()
{
    string S1 = "abc", S2 = "ad";
    int N1 = S1.length(), N2 = S2.length();
 
    minOperations(S1, S2, N1, N2);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the minimum number of
// operations required to make String S1
// contains only characters from the String S2
static void minOperations(String S1, String S2,
                   int N1, int N2)
{
   
    // Stores the minimum of operations
    // required
    int minOpr = 0;
 
    for (int i = 0; i < N1; i++) {
 
        // Check character S1.charAt(i) is not
        // present in S2
        if (S2.contains(String.valueOf(S1.charAt(i)))) {
            continue;
        }
 
        // Stores the minimum operations required
        // for the current character S1.charAt(i)
        int curMinOpr = Integer.MAX_VALUE;
 
        for (int j = 0; j < N2; j++) {
 
            // Check S1.charAt(i) alphabet is greater
            // than the S2.charAt(j) alphabet
            if (S1.charAt(i) > S2.charAt(j)) {
 
                // Find the minimum operations
                // required to make the
                // character S1.charAt(i) to S2.charAt(j)
                curMinOpr
                    = Math.min(curMinOpr,
                          (Math.min(S1.charAt(i) - S2.charAt(j),
                               26 - (S1.charAt(i) - 'a')
                                   + (S2.charAt(j) - 'a'))));
            }
            else {
 
                // Find the minimum operations
                // required to make the
                // character S1.charAt(i) to S2.charAt(j)
                curMinOpr = Math.min(
                    curMinOpr,
                    (Math.min(S2.charAt(j) - S1.charAt(i),
                         (S1.charAt(i) - 'a')
                             + (26 - (S2.charAt(j) - 'a')))));
            }
        }
 
        // Update the value of minOpr
        minOpr += curMinOpr;
    }
 
    // Print the value of minOpr
    System.out.print(minOpr +"\n");
}
 
// Driver code
public static void main(String[] args)
{
    String S1 = "abc", S2 = "ad";
    int N1 = S1.length(), N2 = S2.length();
 
    minOperations(S1, S2, N1, N2);
}
}
 
// This code is contributed by shikhasingrajput

Python3




# Python code for the above approach
def present(S2, c):
    for i in range(len(S2)):
        if S2[i] == c:
            return 1
    return 0
 
# Function to find the minimum number of
# operations required to make string S1
# contains only characters from the string S2
def minOperations(S1, S2, N1, N2):
 
    # Stores the minimum of operations
    # required
    minOpr = 0
 
    for i in range(N1):
 
        # Check character S1[i] is not
        # present in S2
        if present(S2, S1[i]):
            continue
 
        # Stores the minimum operations required
        # for the current character S1[i]
        curMinOpr = 10 ** 9
 
        for j in range(N2):
 
            # Check S1[i] alphabet is greater
            # than the S2[j] alphabet
            if ord(S1[i]) > ord(S2[j]):
 
                # Find the minimum operations
                # required to make the
                # character S1[i] to S2[j]
                curMinOpr = min(
                    curMinOpr,
                    (
                        min(
                            ord(S1[i]) - ord(S2[j]),
                            26
                            - (ord(S1[i]) - ord("a"))
                            + (ord(S2[j]) - ord("a")),
                        )
                    ),
                )
 
            else:
                # Find the minimum operations
                # required to make the
                # character S1[i] to S2[j]
                curMinOpr = min(
                    curMinOpr,
                    (
                        min(
                            ord(S2[j]) - ord(S1[i]),
                            (ord(S1[i]) - ord("a"))
                            + (26 - (ord(S2[j]) - ord("a"))),
                        )
                    ),
                )
 
        # Update the value of minOpr
        minOpr += curMinOpr
 
    # Print the value of minOpr
    print(minOpr)
 
# Driver code
S1 = "abc"
S2 = "ad"
N1 = len(S1)
N2 = len(S2)
 
minOperations(S1, S2, N1, N2)
 
# This code is contributed by gfgking

C#




// C# program for the above approach
using System;
class GFG
{
     
static bool present(string S2, char c) {
    for (int i = 0; i < S2.Length; i++) {
        if (S2[i] == c) {
            return true;
        }
    }
    return false;
}
     
// Function to find the minimum number of
// operations required to make string S1
// contains only characters from the string S2
static void minOperations(string S1, string S2,
                   int N1, int N2)
{
   
    // Stores the minimum of operations
    // required
    int minOpr = 0;
 
    for (int i = 0; i < N1; i++) {
 
        // Check character S1[i] is not
        // present in S2
        if (present(S2, S1[i])) {
            continue;
        }
 
        // Stores the minimum operations required
        // for the current character S1[i]
        int curMinOpr = Int32.MaxValue;
 
        for (int j = 0; j < N2; j++) {
 
            // Check S1[i] alphabet is greater
            // than the S2[j] alphabet
            if (S1[i] > S2[j]) {
 
                // Find the minimum operations
                // required to make the
                // character S1[i] to S2[j]
                curMinOpr
                    = Math.Min(curMinOpr,
                          (Math.Min(S1[i] - S2[j],
                               26 - (S1[i] - 'a')
                                   + (S2[j] - 'a'))));
            }
            else {
 
                // Find the minimum operations
                // required to make the
                // character S1[i] to S2[j]
                curMinOpr = Math.Min(
                    curMinOpr,
                    (Math.Min(S2[j] - S1[i],
                         (S1[i] - 'a')
                             + (26 - (S2[j] - 'a')))));
            }
        }
 
        // Update the value of minOpr
        minOpr += curMinOpr;
    }
 
    // Print the value of minOpr
    Console.WriteLine(minOpr);
}
 
// Driver code
public static void Main()
{
    string S1 = "abc", S2 = "ad";
    int N1 = S1.Length, N2 = S2.Length;
 
    minOperations(S1, S2, N1, N2);
}
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
       // JavaScript code for the above approach
       function present(S2, c) {
           for (let i = 0; i < S2.length; i++) {
               if (S2[i] == c) {
                   return 1;
               }
           }
           return 0;
       }
        
       // Function to find the minimum number of
       // operations required to make string S1
       // contains only characters from the string S2
       function minOperations(S1, S2,
           N1, N2)
       {
        
           // Stores the minimum of operations
           // required
           let minOpr = 0;
 
           for (let i = 0; i < N1; i++) {
 
               // Check character S1[i] is not
               // present in S2
               if (present(S2, S1[i])) {
                   continue;
               }
 
               // Stores the minimum operations required
               // for the current character S1[i]
               let curMinOpr = Number.MAX_VALUE;
 
               for (let j = 0; j < N2; j++) {
 
                   // Check S1[i] alphabet is greater
                   // than the S2[j] alphabet
                   if (S1[i].charCodeAt(0) > S2[j].charCodeAt(0)) {
 
                       // Find the minimum operations
                       // required to make the
                       // character S1[i] to S2[j]
                       curMinOpr
                           = Math.min(curMinOpr,
                               (Math.min(S1[i].charCodeAt(0) - S2[j].charCodeAt(0),
                                   26 - (S1[i].charCodeAt(0) - 'a'.charCodeAt(0))
                                   + (S2[j].charCodeAt(0) - 'a'.charCodeAt(0)))));
                   }
                   else {
 
                       // Find the minimum operations
                       // required to make the
                       // character S1[i] to S2[j]
                       curMinOpr = Math.min(
                           curMinOpr,
                           (Math.min(S2[j].charCodeAt(0) - S1[i].charCodeAt(0),
                               (S1[i].charCodeAt(0) - 'a'.charCodeAt(0))
                               + (26 - (S2[j].charCodeAt(0) - 'a'.charCodeAt(0))))));
                   }
               }
 
               // Update the value of minOpr
               minOpr += curMinOpr;
           }
 
           // Print the value of minOpr
           document.write(minOpr + "<br>")
       }
 
       // Driver code
       let S1 = "abc", S2 = "ad";
       let N1 = S1.length, N2 = S2.length;
 
       minOperations(S1, S2, N1, N2);
 
 // This code is contributed by Potta Lokesh
   </script>

 
 

Output
2

Time Complexity: O(N1 * N2) where N1 and N2 are the size of S1 and S2 respectively
Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!