Minimum number of adjacent swaps to convert a string into its given anagram - GeeksforGeeks

08 Jun, 2021
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.Examples:  
Input: s1 = “abcd”, s2 = “cdab” Output: 4 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” Output:17  
 
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:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function that returns true if s1// and s2 are anagrams of each otherbool isAnagram(string s1, string s2){    sort(s1.begin(), s1.end());    sort(s2.begin(), s2.end());    if (s1 == s2)        return 1;    return 0;} // Function to return the minimum swaps requiredint CountSteps(string s1, string s2, int size){    int i = 0, j = 0;    int result = 0;     // Iterate over the first string and convert    // every element equal to the second string    while (i < size) {        j = i;         // Find index element of first string which        // is equal to the ith element of second string        while (s1[j] != s2[i]) {            j += 1;        }         // Swap adjacent elements in first string so        // that element at ith position becomes equal        while (i < j) {             // Swap elements using temporary variable            char temp = s1[j];            s1[j] = s1[j - 1];            s1[j - 1] = temp;            j -= 1;            result += 1;        }        i += 1;    }    return result;} // Driver codeint main(){    string s1 = "abcd";    string s2 = "cdab";     int size = s2.size();     // If both the strings are anagrams    // of each other then only they    // can be made equal    if (isAnagram(s1, s2))        cout << CountSteps(s1, s2, size);    else        cout << -1;     return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic boolean isAnagram(String s1, String s2){    s1 = sortString(s1);    s2 = sortString(s2);    return (s1.equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){    // convert input string to char array    char tempArray[] = inputString.toCharArray();         // sort tempArray    Arrays.sort(tempArray);         // return new sorted string    return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){    int i = 0, j = 0;    int result = 0;     // Iterate over the first string and convert    // every element equal to the second string    while (i < size)    {        j = i;         // Find index element of first string which        // is equal to the ith element of second string        while (s1[j] != s2[i])        {            j += 1;        }         // Swap adjacent elements in first string so        // that element at ith position becomes equal        while (i < j)        {             // Swap elements using temporary variable            char temp = s1[j];            s1[j] = s1[j - 1];            s1[j - 1] = temp;            j -= 1;            result += 1;        }        i += 1;    }    return result;} // Driver codepublic static void main(String[] args){    String s1 = "abcd";    String s2 = "cdab";     int size = s2.length();     // If both the strings are anagrams    // of each other then only they    // can be made equal    if (isAnagram(s1, s2))        System.out.println(CountSteps(s1.toCharArray(), s2.toCharArray(), size));    else        System.out.println(-1);}} // This code is contributed by Rajput-Ji
# Python3 implementation of the above approach # Function that returns true if s1# and s2 are anagrams of each otherdef isAnagram(s1, s2) :    s1 = list(s1);    s2 = list(s2);    s1 = s1.sort();    s2 = s2.sort();         if (s1 == s2) :        return 1;             return 0; # Function to return the minimum swaps requireddef CountSteps(s1, s2, size) :    s1 = list(s1);    s2 = list(s2);         i = 0;    j = 0;    result = 0;         # Iterate over the first string and convert    # every element equal to the second string    while (i < size) :        j = i;                 # Find index element of first string which        # is equal to the ith element of second string        while (s1[j] != s2[i]) :            j += 1;                     # Swap adjacent elements in first string so        # that element at ith position becomes equal        while (i < j) :                         # Swap elements using temporary variable            temp = s1[j];            s1[j] = s1[j - 1];            s1[j - 1] = temp;            j -= 1;            result += 1;                     i += 1;             return result; # Driver codeif __name__ == "__main__":     s1 = "abcd";    s2 = "cdab";     size = len(s2);     # If both the strings are anagrams    # of each other then only they    # can be made equal    if (isAnagram(s1, s2)) :        print(CountSteps(s1, s2, size));    else :        print(-1); # This code is contributed by AnkitRai01
// C# implementation of the above approachusing System;using System.Linq; class GFG{ // Function that returns true if s1// and s2 are anagrams of each otherstatic Boolean isAnagram(String s1, String s2){    s1 = sortString(s1);    s2 = sortString(s2);    return (s1.Equals(s2));} // Method to sort a string alphabeticallypublic static String sortString(String inputString){    // convert input string to char array    char []tempArray = inputString.ToCharArray();         // sort tempArray    Array.Sort(tempArray);         // return new sorted string    return new String(tempArray);} // Function to return the minimum swaps requiredstatic int CountSteps(char []s1, char[] s2, int size){    int i = 0, j = 0;    int result = 0;     // Iterate over the first string and convert    // every element equal to the second string    while (i < size)    {        j = i;         // Find index element of first string which        // is equal to the ith element of second string        while (s1[j] != s2[i])        {            j += 1;        }         // Swap adjacent elements in first string so        // that element at ith position becomes equal        while (i < j)        {             // Swap elements using temporary variable            char temp = s1[j];            s1[j] = s1[j - 1];            s1[j - 1] = temp;            j -= 1;            result += 1;        }        i += 1;    }    return result;} // Driver codepublic static void Main(String[] args){    String s1 = "abcd";    String s2 = "cdab";     int size = s2.Length;     // If both the strings are anagrams    // of each other then only they    // can be made equal    if (isAnagram(s1, s2))        Console.WriteLine(CountSteps(s1.ToCharArray(), s2.ToCharArray(), size));    else        Console.WriteLine(-1);}} /* This code is contributed by PrinciRaj1992 */
<script>    // Javascript implementation of the above approach         // Function that returns true if s1    // and s2 are anagrams of each other    function isAnagram(s1, s2)    {        s1 = sortString(s1);        s2 = sortString(s2);        return (s1 == s2);    }     // Method to sort a string alphabetically    function sortString(inputString)    {        // convert input string to char array        let tempArray = inputString.split('');         // sort tempArray        tempArray.sort();         // return new sorted string        return tempArray.join("");    }     // Function to return the minimum swaps required    function CountSteps(s1, s2, size)    {        let i = 0, j = 0;        let result = 0;         // Iterate over the first string and convert        // every element equal to the second string        while (i < size)        {            j = i;             // Find index element of first string which            // is equal to the ith element of second string            while (s1[j] != s2[i])            {                j += 1;            }             // Swap adjacent elements in first string so            // that element at ith position becomes equal            while (i < j)            {                 // Swap elements using temporary variable                let temp = s1[j];                s1[j] = s1[j - 1];                s1[j - 1] = temp;                j -= 1;                result += 1;            }            i += 1;        }        return result;    }         let s1 = "abcd";    let s2 = "cdab";       let size = s2.length;       // If both the strings are anagrams    // of each other then only they    // can be made equal    if (isAnagram(s1, s2))        document.write(CountSteps(s1.split(''), s2.split(''), size) + "</br>");    else        document.write(-1 + "</br>");     </script>
4
 
Rajput-Ji
ankthon
princiraj1992
divyeshrabadiya07
anagram
Constructive Algorithms
Strings
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews