Given two strings of equal lengths str1 and str2 consisting of characters ‘a’ and ‘b’ only. The followig operations can be performed on str1:
- Any character can be changed from ‘a’ to ‘b’ or from ‘b’ to ‘a’ with 1 unit cost.
- 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.
Input: str1 = “abb”, str2 = “baa”
Swap(str1, str1), str1 = “bab” and cost = 1
Change str1 = ‘b’ to ‘a’, str1 = “baa” and cost = 2
Input: str1 = “abab”, str2 = “aabb”
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 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 compares 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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check whether str1 can be converted to str2 with the given operations
- Count of characters in str1 such that after deleting anyone of them str1 becomes str2
- Largest substring of str2 which is a prefix of str1
- Generate all possible strings such that char at index i is either str1[i] or str2[i]
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Minimize cost to convert given two integers to zero using given operations
- Transform string str1 into str2 by taking characters from string str3
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum cost to sort strings using reversal operations of different costs
- Minimum cost to convert string into palindrome
- Minimum reduce operations to convert a given string into a palindrome
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum given operations required to convert a given binary string to all 1's
- Minimum number of operations to convert a given sequence into a Geometric Progression
- Minimum number of given operations required to convert a string to another string