Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIMinimum cost to convert str1 to str2 with the given operations

Minimum cost to convert str1 to str2 with the given operations

Given two strings of equal lengths str1 and str2 consist of characters ‘a’ and ‘b’ only. The following operations can be performed on str1

  1. Any character can be changed from ‘a’ to ‘b’ or from ‘b’ to ‘a’ with 1 unit cost.
  2. Any two characters str1[i] and str1[j] can be swapped with cost |i – j|.

The task is to find the minimum cost required to convert str1 to str2.

Examples: 

Input: str1 = “abb”, str2 = “baa” 
Output:
Explanation: Swap(str1[0], str1[1]), str1 = “bab” and cost = 1 
Change str1[2] = ‘b’ to ‘a’, str1 = “baa” and cost = 2

Input: str1 = “abab”, str2 = “aabb” 
Output:

Approach: It can be observed that swapping will only be performed on consecutive characters because if the characters are not consecutive then the cost of swapping will be ? 2 which will give a cost greater than or equal to the cost of changing those characters using the operation of the first type. Now, for every two consecutive characters if they are different in both the string then swap these characters incurring 1 unit cost as compared to 2 unit cost when both of them are changed separately. Else change the character which is different in both the strings (either the current or the next). Finally, print the calculated cost.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum
// cost to convert str1 to sr2
int minCost(string str1, string str2, int n)
{
    int cost = 0;
 
    // For every character of str1
    for (int i = 0; i < n; i++) {
 
        // If current character is not
        // equal in both the strings
        if (str1[i] != str2[i]) {
 
            // If the next character is also different in both
            // the strings then these characters can be swapped
            if (i < n - 1 && str1[i + 1] != str2[i + 1]) {
                swap(str1[i], str1[i + 1]);
                cost++;
            }
 
            // Change the current character
            else {
                cost++;
            }
        }
    }
    return cost;
}
 
// Driver code
int main()
{
    string str1 = "abb", str2 = "bba";
    int n = str1.length();
 
    cout << minCost(str1, str2, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the minimum
// cost to convert str1 to sr2
static int minCost(char []str1,
                   char []str2, int n)
{
    int cost = 0;
 
    // For every character of str1
    for (int i = 0; i < n; i++)
    {
 
        // If current character is not
        // equal in both the strings
        if (str1[i] != str2[i])
        {
 
            // If the next character is also different in both
            // the strings then these characters can be swapped
            if (i < n - 1 && str1[i + 1] != str2[i + 1])
            {
                swap(str1, i, i + 1);
                cost++;
            }
 
            // Change the current character
            else
            {
                cost++;
            }
        }
    }
    return cost;
}
 
static void swap(char []arr, int i, int j)
{
    char temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
 
// Driver code
public static void main(String[] args)
{
    String str1 = "abb", str2 = "bba";
    int n = str1.length();
 
    System.out.println(minCost(str1.toCharArray(),
                               str2.toCharArray(), n));
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 implementation of the approach
 
# Function to return the minimum
# cost to convert str1 to sr2
def minCost(str1, str2, n):
 
    cost = 0
 
    # For every character of str1
    for i in range(n):
 
        # If current character is not
        # equal in both the strings
        if (str1[i] != str2[i]):
 
            # If the next character is also different in both
            # the strings then these characters can be swapped
            if (i < n - 1 and str1[i + 1] != str2[i + 1]):
                swap(str1[i], str1[i + 1])
                cost += 1
             
            # Change the current character
            else:
                cost += 1
             
    return cost
 
# Driver code
if __name__ == '__main__':
 
    str1 = "abb"
    str2 = "bba"
    n = len(str1)
 
    print(minCost(str1, str2, n))
 
# This code is contributed by ashutosh450


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the minimum
    // cost to convert str1 to sr2
    static int minCost(string str1,
                       string str2, int n)
    {
        int cost = 0;
     
        char[] array = str1.ToCharArray();
         
        // For every character of str1
        for (int i = 0; i < n; i++)
        {
     
            // If current character is not
            // equal in both the strings
            if (str1[i] != str2[i])
            {
     
                // If the next character is also different in both
                // the strings then these characters can be swapped
                if (i < n - 1 && str1[i + 1] != str2[i + 1])
                {
                    char temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp ;
                     
                    cost++;
                }
     
                // Change the current character
                else
                {
                    cost++;
                }
            }
        }
        return cost;
    }
     
    // Driver code
    static public void Main ()
    {
        string str1 = "abb", str2 = "bba";
        int n = str1.Length;
     
        Console.WriteLine(minCost(str1, str2, n));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the minimum
    // cost to convert str1 to sr2
    function minCost(str1, str2, n)
    {
        let cost = 0;
       
        let array = str1.split('');
           
        // For every character of str1
        for (let i = 0; i < n; i++)
        {
       
            // If current character is not
            // equal in both the strings
            if (str1[i] != str2[i])
            {
       
                // If the next character is also different in both
                // the strings then these characters can be swapped
                if (i < n - 1 && str1[i + 1] != str2[i + 1])
                {
                    let temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp ;
                       
                    cost++;
                }
       
                // Change the current character
                else
                {
                    cost++;
                }
            }
        }
        return cost;
    }
     
    let str1 = "abb", str2 = "bba";
    let n = str1.length;
 
    document.write(minCost(str1, str2, n));
 
// This code is contributed by divyeshrabadiya07.
</script>


Output

2

Time Complexity: O(n)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments