Program to count number of unique palindromes we can make using string characters in Python


Suppose we have a string s, we have to find the number of distinct palindromes we can generate using all characters. If the answer is very large then mod the result by 10^9 + 7.

So, if the input is like s = "xyzzy", then the output will be 2, as we can make "zyxyz" and "yzxzy"

To solve this, we will follow these steps −

  • m = 10^9+7

  • char_freq := a map holding each character of s and their frequencies

  • odd := 0

  • for each character k and frequency v in char_freq, do

    • if v mod 2 is 1, then

      • odd := odd + 1

  • if odd > 1, then

    • return 0

  • half_length := quotient of (size of s) / 2

  • res := factorial of half_length

  • dividor := 1

  • for each character k and frequency v in char_freq, do

    • dividor := dividor * factorial of (quotient of v/2)

  • return (quotient of res/dividor) mod m


Let us see the following implementation to get better understanding −

Example

 Live Demo

from math import factorial
class Solution:
   def solve(self, s):
      m = (10**9+7)
      char_freq = {}
      for c in s:
         char_freq[c] = char_freq.get(c, 0) + 1

      odd = 0
      for k,v in char_freq.items():
         if v % 2 == 1:
            odd +=1
      if odd > 1:
         return 0

      half_length = len(s)//2
      res = factorial(half_length)
      dividor = 1
      for k,v in char_freq.items():
         dividor *= factorial(v//2)

   return (res//dividor) % m
ob = Solution()
print(ob.solve("xyzzy"))

Input

"xyzzy"

Output

2

Updated on: 07-Oct-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements