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

When working with palindromes, we need to understand that a palindrome reads the same forwards and backwards. To count unique palindromes from string characters, we use combinatorial mathematics to calculate arrangements of the first half of the palindrome.

Algorithm Overview

The key insight is that for a palindrome to be possible, at most one character can have an odd frequency (this becomes the middle character). We then calculate arrangements of the first half using factorial division ?

Step-by-Step Approach

  • Count frequency of each character in the string

  • Check if palindrome formation is possible (at most one odd frequency)

  • Calculate arrangements of the first half using the formula: n! / (n1! × n2! × ... × nk!)

  • Return result modulo 10^9 + 7

Implementation

from math import factorial

class Solution:
    def solve(self, s):
        m = (10**9 + 7)
        char_freq = {}
        
        # Count frequency of each character
        for c in s:
            char_freq[c] = char_freq.get(c, 0) + 1

        # Count characters with odd frequency
        odd = 0
        for k, v in char_freq.items():
            if v % 2 == 1:
                odd += 1
        
        # If more than one character has odd frequency, no palindrome possible
        if odd > 1:
            return 0

        # Calculate arrangements of first half
        half_length = len(s) // 2
        res = factorial(half_length)
        divisor = 1
        
        for k, v in char_freq.items():
            divisor *= factorial(v // 2)

        return (res // divisor) % m

# Test the solution
ob = Solution()
print(ob.solve("xyzzy"))
2

How It Works

For the string "xyzzy":

  • Character frequencies: {'x':1, 'y':2, 'z':2}

  • Only 'x' has odd frequency (1), so palindrome is possible

  • Half length = 5 // 2 = 2

  • Arrangements = 2! / (0! × 1! × 1!) = 2 / 1 = 2

Example with Another String

from math import factorial

def count_palindromes(s):
    m = (10**9 + 7)
    char_freq = {}
    
    for c in s:
        char_freq[c] = char_freq.get(c, 0) + 1
    
    odd_count = sum(1 for freq in char_freq.values() if freq % 2 == 1)
    
    if odd_count > 1:
        return 0
    
    half_length = len(s) // 2
    numerator = factorial(half_length)
    denominator = 1
    
    for freq in char_freq.values():
        denominator *= factorial(freq // 2)
    
    return (numerator // denominator) % m

# Test with different strings
test_cases = ["aab", "abc", "aabb"]
for test in test_cases:
    result = count_palindromes(test)
    print(f"String: '{test}' ? Unique palindromes: {result}")
String: 'aab' ? Unique palindromes: 1
String: 'abc' ? Unique palindromes: 0
String: 'aabb' ? Unique palindromes: 2

Key Points

  • A palindrome can have at most one character with odd frequency

  • We only arrange the first half; the second half is determined by palindrome property

  • The formula uses factorial division to handle repeated characters

  • Result is modulo 10^9 + 7 to handle large numbers

Conclusion

This solution efficiently counts unique palindromes by checking frequency constraints and using combinatorial mathematics. The key insight is that only the first half arrangement matters in palindrome formation.

Updated on: 2026-03-25T11:02:57+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements