Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimize count of given operations required to make two given strings permutations of each other
Next article icon

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

Last Updated : 12 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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)


 


Next Article
Minimize count of given operations required to make two given strings permutations of each other
author
dharanendralv23
Improve
Article Tags :
  • Strings
  • Algo Geek
  • DSA
  • Algo-Geek 2021
Practice Tags :
  • Strings

Similar Reads

  • Minimize length of prefix of string S containing all characters of another string T
    Given two string S and T, the task is to find the minimum length prefix from S which consists of all characters of string T. If S does not contain all characters of string T, print -1. Examples: Input: S = "MarvoloGaunt", T = "Tom" Output: 12 Explanation: The 12 length prefix "MarvoloGaunt" contains
    7 min read
  • Minimize the count of characters to be added or removed to make String repetition of same substring
    Given a string S consisting of N characters, the task is to modify the string S by performing the minimum number of following operations such that the modified string S is the concatenation of its half. Insert any new character at any index in the string.Remove any character from the string S.Replac
    15+ min read
  • Find minimum operations to make all characters of a string identical
    Given a string of size N, the task is to find the minimum operation required in a string such that all elements of a string are the same. In one operation, you can choose at least one character from the string and remove all chosen characters from the string, but you can't choose an adjacent charact
    11 min read
  • Minimize count of given operations required to make two given strings permutations of each other
    Given two strings str1 and str2, the task is to count the minimum number of operations of the following three types on one of the two strings that are required to make str1 and str2 permutations of each other: Insert a character into the string.Remove a character from the string.Replace a character
    13 min read
  • Minimize partitions in given string to get another string
    Given two strings A and B, print the minimum number of slices required in A to get another string B. In case, if it is not possible to get B from A, then print "-1". Examples : Input: A = "geeksforgeeks", B = "ksgek"Output: 5Explanation: g | ee | ks | forge | ek | s : minimum 5 slices are required t
    15+ min read
  • Smallest window in a String containing all characters of other String
    Given two strings s (length m) and p (length n), the task is to find the smallest substring in s that contains all characters of p, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index. Ex
    15+ min read
  • Remove minimum characters from string to split it into three substrings under given constraints
    Given a string str of lowercase alphabets, the task is to remove minimum characters from the given string so that string can be break into 3 substrings str1, str2, and str3 such that each substring can be empty or can contains only characters 'a', 'b', and 'c' respectively.Example: Input: str = "aaa
    8 min read
  • Minimum operations to convert String A to String B
    Given two strings consisting of lowercase alphabets A and B, both of the same length. Each character of both the strings is either a lowercase letter or a question mark '?'. The task is to find the minimum number of operations required to convert A to B, in one operation you can choose an index i, i
    12 min read
  • Smallest string containing all unique characters from given array of strings
    Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are u
    9 min read
  • Minimum number of given operations required to make two strings equal
    Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations: If _ is at position i then _ can be swapped w
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences