Open In App

Minimum number of adjacent swaps to reverse a String

Last Updated : 30 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string s. The task is to minimize the number of adjacent swaps required to reverse the string. 

Examples:

Input: s = “abc”
Output: 3
Explanation: Follow the operations below to solve the given problem.
swap(1, 2)->  “bac”
swap(2, 3)-> “bca”
swap(1, 2)-> “cba”

Input: s = “ba”
Output: 1

 

Approach: This problem can be solved by comparing the given string with its reverse and counting the number of swaps required to form the reversed string. Follow the steps below to solve the problem:

  • Initialize a string s2 as the copy of the original string s.
  • reverse string s2
  • Initialize result = 0, to store the number of adjacent swaps required to reverse the string.
  • Iterate using two pointers i and j for both the strings and find each occurrence of s in s2 through two pointers i and j
    • Each time set result = result + j – i.
  • Return result as the final answer.

Below is the implementation of the above approach:

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum adjacent swaps
// Required to reverse the string
int min_swaps(string s)
{
    string s2 = s;
 
    // Reverse a string
    reverse(s2.begin(), s2.end());
 
    int i = 0, j = 0;
    int result = 0;
    int n = s.length();
    while (i < n) {
 
        j = i;
 
        // Iterate till characters
        // of both the strings match
        while (s[j] != s2[i]) {
            j += 1;
        }
 
        // Iterating until i=j
        // result will be j-i
        while (i < j) {
            char temp = s[j];
            s[j] = s[j - 1];
            s[j - 1] = temp;
            j -= 1;
            result += 1;
        }
        i += 1;
    }
    return result;
}
 
// Driver code
int main()
{
    string s = "abc";
 
    cout << min_swaps(s);
    return 0;
}


Java




// Java program for above approach
public class GFG {
     
    static int min_swaps(String s)
    {
        String s2 = "";
 
        // Reverse a string
        char[] cArray = s.toCharArray();
        for (int k = cArray.length - 1; k > -1; k--) {
            s2 += cArray[k];
        }
 
        int i = 0, j = 0;
        int result = 0;
        int n = s.length();
        while (i < n) {
 
            j = i;
 
            // Iterate till characters
            // of both the strings match
            while (s.charAt(j) != s2.charAt(i)) {
                j += 1;
            }
 
            // Iterating until i=j
            // result will be j-i
            while (i < j) {
                char temp = s.charAt(j);
                char[] ch = s.toCharArray();
                ch[j] = ch[j - 1];
                ch[j - 1] = temp;
                s = new String(ch);
                j -= 1;
                result += 1;
            }
            i += 1;
        }
        return result;
    }
 
    // Driver code
    static public void main(String []args)
    {
        String s = "abc";
 
        System.out.println(min_swaps(s));
    }
}
 
// This code is contributed by AnkThon


Python3




# python program for above approach
 
# Function to find minimum adjacent swaps
# Required to reverse the string
def min_swaps(s):
 
    s2 = s.copy()
 
    # Reverse a string
    s2.reverse()
 
    i = 0
    j = 0
    result = 0
    n = len(s)
    while (i < n):
 
        j = i
 
        # Iterate till characters
        # of both the strings match
        while (s[j] != s2[i]):
            j += 1
 
            # Iterating until i=j
            # result will be j-i
        while (i < j):
            temp = s[j]
            s[j] = s[j - 1]
            s[j - 1] = temp
            j -= 1
            result += 1
 
        i += 1
 
    return result
 
# Driver code
if __name__ == "__main__":
 
    s = "abc"
    s = list(s)
    print(min_swaps(s))
 
    # This code is contributed by rakeshsahni


C#




using System;
 
public class GFG {
    static int min_swaps(string s)
    {
        string s2 = String.Empty;
 
        // Reverse a string
        char[] cArray = s.ToCharArray();
        for (int k = cArray.Length - 1; k > -1; k--) {
            s2 += cArray[k];
        }
 
        int i = 0, j = 0;
        int result = 0;
        int n = s.Length;
        while (i < n) {
 
            j = i;
 
            // Iterate till characters
            // of both the strings match
            while (s[j] != s2[i]) {
                j += 1;
            }
 
            // Iterating until i=j
            // result will be j-i
            while (i < j) {
                char temp = s[j];
                char[] ch = s.ToCharArray();
                ch[j] = ch[j - 1];
                ch[j - 1] = temp;
                s = new string(ch);
                j -= 1;
                result += 1;
            }
            i += 1;
        }
        return result;
    }
 
    // Driver code
    static public void Main()
    {
        string s = "abc";
 
        Console.WriteLine(min_swaps(s));
    }
}
 
// This code is contributed by maddler.


Javascript




<script>
 
// Javascript program for above approach
 
// Function to find minimum adjacent swaps
// Required to reverse the string
function min_swaps(s)
{
 
    var s2 = JSON.parse(JSON.stringify(s));
    s = s.split('');
    s2 = s2.split('');
 
    // Reverse a string
    s2.reverse();
    var i = 0, j = 0;
    var result = 0;
    var n = s.length;
    while (i < n) {
 
        j = i;
 
        // Iterate till characters
        // of both the strings match
        while (s[j] != s2[i]) {
            j += 1;
        }
 
        // Iterating until i=j
        // result will be j-i
        while (i < j) {
            var temp = s[j];
            s[j] = s[j - 1];
            s[j - 1] = temp;
            j -= 1;
            result += 1;
        }
        i += 1;
    }
    return result;
}
 
// Driver code
var s = "abc";
document.write(min_swaps(s));
 
// This code is contributed by rutvik_56.
</script>


Output: 

3

 

Time Complexity: O(N2), Where N is the size of the given string.
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads