Minimize operations to make one string contain only characters from other string
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.
Input: S1 = “abc”, S2 = “ad”
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”
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:
Time Complexity: O(N1 * N2) where N1 and N2 are the size of S1 and S2 respectively
Auxiliary Space: O(1)