Count of Palindromic Strings possible by swapping of a pair of Characters
Given a palindromic string S, the task is to find the count of palindromic strings possible by swapping a pair of character at a time.
Input: s = “abba”
1st Swap: abba -> abba
2nd Swap: abba -> abba
All other swaps will lead to a non-palindromic string.
Therefore, the count of possible strings is 2.
Input: s = “aaabaaa”
The simplest approach to solve the problem is to generate all possible pair of characters from the given string and for each pair if swapping them generates a palindromic string or not. If found to be true, increase count. Finally, print the value of count.
Time Complexity: O(N3)
Auxiliary Space: O(1)
To optimize the above-mentioned approach, calculate the frequencies of each character in the string. For the string to remain a palindrome, only the same character can be swapped in the string.
Follow the steps below to solve the problem:
- Traverse the string.
- For every ith character, increase count with the current frequency of the character. This increases the number of swaps the current character can make with its previous occurrences.
- Increase the frequency of the ith character.
- Finally, after complete traversal of the string, print count.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.