Convert characters of string1 to characters present in string2 by incrementing or decrementing lexicographically


In this problem, programmers require to make all characters of str1 equal to any character of str2 by performing the increment or decrement operation. Also, we can increment or decrement rotationally. It means ‘z’ + 1 ==‘a’ and ‘a’ – 1 == ‘z’.

We can solve the problem by finding the minimum cost of making the str1 string’s character equal to any character of the string str2. For each character, we can find the minimum required operations and sum them all.

Problem statement – We have given two strings named str1 and str2. The size of the str1 is N, and the size of str2 is M. Also, the given condition is N <= M or N > M. Both strings contain only lowercase alphabetical characters. The task is we need to make all characters of str1 equal to any character of str2 by increment or decrement operation. We need to find such minimum required operations to make all characters of str1 equal to any character of str2.

Sample examples

Input

str1 = "aedc", str2 = "db";

Output

3

Explanation

  • We can make ‘a’ equal to ‘b’, and its cost is 1.

  • We can make ‘e’ equal to ‘d’; its cost is 1.

  • The ‘d’ already exists in the str2, so the cost is 0.

  • We can make ‘c’ equal to b or d; the cost will be 1.

So, the total required cost or number of required operations is 3.

Input

str1 = "mwerd", str2 = "dermw";

Output

0

Explanation – All characters of str1 exist in str2. So, the required operations are equal to zero.

Input

str1 = "bdfhjlnp", str2 = "acegikmo";

Output

8

Explanation – We can make each character of str1 equal to any character of str2 by incrementing or decrementing the character by 1. For example, ‘b’ -> ‘a’, ‘d’ -> ‘c’ or ‘d’ -> ‘e’, etc.

Approach 1

We will take any character of the str1 string and make it equal to each character of str2 by performing the increment or decrement operations. After that, we will find the minimum cost for each character of str1 and sum them all.

Let’s understand both ways to make one character equal to another character.

  • Converting the character ‘a’ to ‘e’.

  • By increment, we need 4 operations to make ‘a’ equal to ‘e’.

  • By decrement operations, we need 26 – 4 = 22 operations.

Here, 4 is the minimum, so we will consider it.

  • Converting the character ‘a’ to ‘y’.

  • By increment, we need 24 operations.

  • By decrement, we need 2 operations.

So, the minimum required operations are 4.

Algorithm

Step 1 – Define the ‘str2Chars’ named unordered hashmap to store the frequency of characters of the str2 string.

Step 2 – Traverse the string and update the frequency of each character in the hashmap.

Step 3 – Define the ‘count’ variable to store the minimum required operations.

Step 4 – Start traversing string 1. In the loop, initialize the minMoves variable with the maximum integer value to store the minimum operations required to make the pth character equal to any character of str2.

Step 5 – Make 1 to 26 iterations using the loop. Get the char value between 0 to 25 by subtracting the ‘a’ from str1[p].

Step 6 – If the current character exists in the hashmap, assign zero to the minMoves variable and break the loop.

Step 7 – Else, if the ‘a’ + q character exists in the hashmap, we can convert the p character to ‘a’ + q.

Step 8 – Get the total operations to make character equal to ‘a’ + q, by increment operations and store into the leftMin variable.

Step 9 – Also, find total operations to make the character equal to ‘a’ + q, by decrement operations and store them into the rightMin variable.

Step 10 – Get minimum from the ‘leftMin’, and ‘rigthMin’. Also, get the minimum from the allMoves, and minMoves.

Step 11 – Add minMoves to the count variable’s value.

Step 12 – Return the ‘count’ value.

Example

#include <bits/stdc++.h>
using namespace std;

int totalOps(string str1, string str2) {
    // Map to store all characters of str2
    unordered_map<char, int> str2Chars;
    // Traverse str2
    for (int p = 0; p < str2.size(); p++) {
        str2Chars[str2[p]]++;
    }
    // Store minimum operations
    int count = 0;
    // Traverse str1
    for (int p = 0; p < str1.size(); p++) {
        // Total minimum move requires converting one character to another
        int minMoves = INT_MAX;
        // Calculate required moves
        for (int q = 0; q < 26; q++) {
            // Get the character value
            int char_val = str1[p] - 'a';
            // If str2 contains the str1[p]
            if (str2Chars[str1[p]] > 0) {
                minMoves = 0;
                break;
            } else if (str2Chars['a' + q] > 0) {
                // Find minimum difference between str1[p] and str2[q]
                int leftMin = abs(char_val - q);
                int RightMin = min((26 - char_val) + q, char_val + (26 - q));
                int allMoves = min(leftMin, RightMin);
                minMoves = min(minMoves, allMoves);
            }
        }
        // Update minimum operations
        count += minMoves;
    }
    // Return total operations
    return count;
}
int main() {
    string str1 = "aedc";
    string str2 = "db";
    cout << "The minimum numbers of operations required to convert str1 to str2 is " << totalOps(str1, str2);
    return 0;
}

Output

The minimum numbers of operations required to convert str1 to str2 is 3

Time complexity – O(N*26) ~ O(N) as we traverse the string.

Space complexity – O(1) as we don’t use constant space.

Similarly, programmers can try to solve the problem in which we need to make all str2 equal to str1. So, we need to take the minimum from increment or decrement operations for converting character at the pth index in str1 to character at the pth index in str2.

Updated on: 24-Aug-2023

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements