Given a string s, the task is to find out the minimum no of swaps required to make string s palindrome. If it is not possible, then return -1.
Input : aabcb
Output : 3
After 1st swap: abacb
After 2nd swap: abcab
After 3rd swap: abcba
Input : adbcdbad
Output : -1
The following are detailed steps to solve this problem.
- 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.
- Till the time we find the same character, keep moving the right pointer to one step left.
- If the same character not found then return -1.
- 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.
- Increase left pointer and repeat step 2.
Below is the implementation of the above approach:
Time Complexity: Since we are running two nested loops on the length of string, the time complexity is O(n)
Auxiliary Space: Since we aren’t using any extra space, so auxiliary space 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.
- Minimum number of deletions to make a string palindrome
- Minimum number of deletions to make a string palindrome | Set 2
- Minimum number of characters to be replaced to make a given string Palindrome
- Minimum characters to be added at front to make string palindrome
- Minimum number of Appends needed to make a string palindrome
- Minimum removal to make palindrome permutation
- Minimum changes required to make each path in a matrix palindrome
- Remove a character from a string to make it a palindrome
- Number of Counterclockwise shifts to make a string palindrome
- Minimum cost to convert string into palindrome
- Count All Palindrome Sub-Strings in a String | Set 2
- Count All Palindrome Sub-Strings in a String | Set 1
- Minimum changes required to make first string substring of second string
- Minimum reduce operations to convert a given string into a palindrome
- Count the nodes of the given tree whose weighted string is a palindrome
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Count of leaf nodes of the tree whose weighted string is a palindrome
- Minimum changes to a string to make all substrings distinct
- Count substring of Binary string such that each character belongs to a palindrome of size greater than 1
- Insert minimum parantheses to make string balanced
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.
Improved By : sapnasingh4991