Skip to content
Related Articles

Related Articles

Count minimum swap to make string palindrome
  • Difficulty Level : Medium
  • Last Updated : 19 Oct, 2020

Given a string s, the task is to find out the minimum no of adjacent swaps required to make string s palindrome. If it is not possible, then return -1.
Examples:

Input: aabcb 
Output:
Explanation: 
After 1st swap: abacb 
After 2nd swap: abcab 
After 3rd swap: abcba
Input: adbcdbad 
Output: -1 

Approach
The following are detailed steps to solve this problem. 

  1. Take two-pointer where the first pointer track from the left side of a string and second pointer keep track from the right side of a string.
  2. Till the time we find the same character, keep moving the right pointer to one step left.
  3. If the same character not found then return -1.
  4. If the same character found then swap the right pointer’s character towards right until it is not placed at it’s correct position in a string.
  5. Increase left pointer and repeat step 2.

Below is the implementation of the above approach: 

C++




// C++ program to Count
// minimum swap to make
// string palindrome
#include <bits/stdc++.h>
using namespace std;
 
// Function to Count minimum swap
int countSwap(string s)
{
    // calculate length of string as n
    int n = s.length();
     
    // counter to count minimum swap
    int count = 0;
 
    // A loop which run till mid of
    // string
    for (int i = 0; i < n / 2; i++) {
        // Left pointer
        int left = i;
 
        // Right pointer
        int right = n - left - 1;
 
        // A loop which run from right
        // pointer towards left pointer
        while (left < right) {
            // if both char same then
            // break the loop.
            // If not, then we have to
            // move right pointer to one
            // position left
            if (s[left] == s[right]) {
                break;
            }
            else {
                right--;
            }
        }
 
        // If both pointers are at same
        // position, it denotes that we
        // don't have sufficient characters
        // to make palindrome string
        if (left == right) {
            return -1;
        }
         
        // else swap and increase the count
        for (int j = right; j < n - left - 1;
                j++) {
            swap(s[j], s[j + 1]);
            count++;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    string s = "geeksfgeeks";
 
    // Function calling
    int ans1 = countSwap(s);
        
    reverse(s.begin(),s.end());
    int ans2 = countSwap(s);
              
    cout<<max(ans1,ans2);
 
    return 0;
}

Java




// Java program to Count
// minimum swap to make
// string palindrome
import java.util.*;
 
class GFG {
 
    // Function to Count minimum swap
    static int countSwap(String str)
    {
     
        // Legth of string
        int n = str.length();
         
        // it will convert string to
        // char array
        char s[] = str.toCharArray();
 
        // Counter to count minimum
        // swap
        int count = 0;
 
        // A loop which run in half
        // string from starting
        for (int i = 0; i < n / 2;
                i++) {
 
            // Left pointer
            int left = i;
 
            // Right pointer
            int right = n - left - 1;
 
            // A loop which run from
            // right pointer to left
            // pointer
            while (left < right) {
 
                // if both char same
                // then break the loop
                // if not same then we
                // have to move right
                // pointer to one step
                // left
                if (s[left] == s[right]) {
                    break;
                }
                else {
                    right--;
                }
            }
 
            // it denotes both pointer at
            // same position and we don't
            // have sufficient char to make
            // palindrome string
            if (left == right) {
                return -1;
            }
            else {
                for (int j = right;
                    j < n - left - 1; j++) {
                    char t = s[j];
                    s[j] = s[j + 1];
                    s[j + 1] = t;
                    count++;
                }
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "geeksfgeeks";
 
        // Function calling
        int ans1 = countSwap(s);
       
        StringBuilder sb=new StringBuilder(s); 
        sb.reverse(); 
        s = sb.toString(); 
 
        int ans2 = countSwap(s);
        if(ans1 > ans2)
          System.out.println(ans1);
        else
          System.out.println(ans2);
    }
}

Python3




''' Python3 program to Count
    minimum swap to make
    string palindrome'''
 
# Function to Count minimum swap
def CountSwap(s, n):
    s = list(s)
 
    # Counter to count minimum swap
    count = 0
    ans = True
 
    # A loop which run in half string
    # from starting
    for i in range(n // 2):
 
        # Left pointer
        left = i
 
        # Right pointer
        right = n - left - 1
 
        # A loop which run from right pointer
        # to left pointer
        while left < right:
 
            # if both char same then
            # break the loop if not
            # same then we have to move
            # right pointer to one step left
            if s[left] == s[right]:
                break
            else:
                right -= 1
 
        # it denotes both pointer at
        # same position and we don't
        # have sufficient char to make
        # palindrome string
        if left == right:
            ans = False
            break
        else:
            for j in range(right, n - left - 1):
                (s[j], s[j + 1]) = (s[j + 1], s[j])
                count += 1
    if ans:
        return (count)
    else:
        return -1
 
 
# Driver Code
s = 'geeksfgeeks'
 
# Legth of string
n = len(s)
 
# Function calling
ans1 = CountSwap(s, n)
ans2 = CountSwap(s[::-1], n)
print(max(ans1, ans2))

C#




// C# program to Count
// minimum swap to make
// string palindrome
using System;
 
class GFG {
  
    // Function to Count minimum swap
    static int countSwap(String str)
    {
      
        // Length of string
        int n = str.Length;
          
        // it will convert string to
        // char array
        char []s = str.ToCharArray();
  
        // Counter to count minimum
        // swap
        int count = 0;
  
        // A loop which run in half
        // string from starting
        for (int i = 0; i < n / 2;
                i++) {
  
            // Left pointer
            int left = i;
  
            // Right pointer
            int right = n - left - 1;
  
            // A loop which run from
            // right pointer to left
            // pointer
            while (left < right) {
  
                // if both char same
                // then break the loop
                // if not same then we
                // have to move right
                // pointer to one step
                // left
                if (s[left] == s[right]) {
                    break;
                }
                else {
                    right--;
                }
            }
  
            // it denotes both pointer at
            // same position and we don't
            // have sufficient char to make
            // palindrome string
            if (left == right) {
                return -1;
            }
            else {
                for (int j = right;
                    j < n - left - 1; j++) {
                    char t = s[j];
                    s[j] = s[j + 1];
                    s[j + 1] = t;
                    count++;
                }
            }
        }
  
        return count;
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "geeksfgeeks";
  
        // Function calling
        int ans1 = countSwap(s);
       
        char[] charArray = s.ToCharArray();
        Array.Reverse( charArray );
        s = new string( charArray );
          
        int ans2 = countSwap(s);
         
        if(ans1 > ans2)
           Console.WriteLine(ans1);
        else
          Console.WriteLine(ans2);
    }
}
 
// This code is contributed by sapnasingh4991
Output: 
9


 

Complexity Analysis 
Time Complexity: Since we are running two nested loops on the length of string, the time complexity is O(n2) 
Auxiliary Space: Since we aren’t using any extra space, Therefore Auxiliary space used is O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :