VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-palindromic-permutations-set-1/

⇱ Number of palindromic permutations | Set 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of palindromic permutations | Set 1

Last Updated : 5 Aug, 2022

Given string str, find count of all palindromic permutations of it.

Examples : 

Input : str = "gfgf"
Output : 2
There are two palindromic 
permutations fggf and gffg

Input : str = "abc"
Output : 0

The idea is based on below facts : 

  • A string can permute to a palindrome if number of odd occurring characters is at most one.
  • One occurrence of the only odd character always goes to middle.
  • Half of counts of all characters decide the result. In case of odd occurring character, it is floor of half. The other half is automatically decided

For example, if input string is "aabbccd", the count of palindromic permutations is 3! (We get three by taking floor of half of all counts)

What if half itself has repeated characters? 
We apply a simple combinatorial rule and divide by factorial of half.
For example "aaaaaabbbb", floor of half of string is 5. In half of a palindromic string, 'a' is repeated three times and 'b' is repeated two times, so our result is (5!) / (2!) * (3!).

Implementation:


Output : 
2

 

The above solution causes overflow very early. We can avoid overflow by doing modular arithmetic. In the next article, we would be discussing modular arithmetic-based approach.

Comment