Given two strings s1 and s2, the task is to find the minimum number of steps required to convert s1 into s2. The only operation allowed is to swap adjacent elements in the first string. Every swap is counted as a single step.
Input: s1 = “abcd”, s2 = “cdab”
Swap 2nd and 3rd element, abcd => acbd
Swap 1st and 2nd element, acbd => cabd
Swap 3rd and 4th element, cabd => cadb
Swap 2nd and 3rd element, cadb => cdab
Minimum 4 swaps are required.
Input: s1 = “abcfdegji”, s2 = “fjiacbdge”
Approach: Use two pointers i and j for first and second strings respectively. Initialise i and j to 0.
Iterate over the first string and find the position j such that s1[j] = s2[i] by incrementing the value to j. Keep on swapping the adjacent elements j and j – 1 and decrement j until it is greater than i.
Now the ith element of the first string is equal to the second string, hence increment the value of i.
This technique will give the minimum number of steps as there are zero unnecessary swaps.
Below is the implementation of the above approach:
- Convert string X to an anagram of string Y with minimum replacements
- Minimum swaps required to convert one binary string to another
- Minimum adjacent swaps to move maximum and minimum to corners
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Minimum number of given operations required to convert a string to another string
- Minimum swaps required to make a binary string alternating
- Remove minimum number of characters so that two strings become anagram
- Number of sub-strings which are anagram of any sub-string of another string
- Minimum number of swaps required to sort an array | Set 2
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
- Generate permutations with only adjacent swaps allowed
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum cost to convert string into palindrome
- Minimum steps to convert one binary string to other only using negation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.