Count maximum-length palindromes in a String
Last Updated :
24 Nov, 2022
Given a string, count how many maximum-length palindromes are present. (It need not be a substring)
Examples:
Input : str = "ababa"
Output: 2
Explanation :
palindromes of maximum of lengths are :
"ababa", "baaab"
Input : str = "ababab"
Output: 4
Explanation :
palindromes of maximum of lengths are :
"ababa", "baaab", "abbba", "babab"
Approach A palindrome can be represented as "str + t + reverse(str)".
Note: "t" is empty for even length palindromic strings
Calculate in how many ways "str" can be made and then multiply with "t" (number of single characters left out).
Let ci be the number of occurrences of a character in the string. Consider the following cases:
- If ci is even. Then half of every maximum palindrome will contain exactly letters fi = ci / 2.
- If ci is odd. Then half of every maximum palindrome will contain exactly letters fi = (ci - 1)/ 2.
Let k be the number of odd ci. If k=0, the length of the maximum palindrome will be even; otherwise it will be odd and there will be exactly k possible middle letters i.e., we can set this letter to the middle of the palindrome.
The number of permutations of n objects with n1 identical objects of type 1, n2 identical objects of type 2, and n3 identical objects of type 3 is n! / (n1! * n2! * n3!).
So here we have total number of characters as fa+fb+fa+.......+fy+fz . So number of permutation is (fa+fb+fa+.......+fy+fz)! / fa! fb!...fy!fz!.
Now If K is not 0, it's obvious that the answer is k * (fa+fb+fa+.......+fy+fz+)! / fa! fb!...fy!fz!
Below is the implementation of the above.
C++
// C++ implementation for counting
// maximum length palindromes
#include <bits/stdc++.h>
using namespace std;
// factorial of a number
int fact(int n)
{
int ans = 1;
for (int i = 1; i <= n; i++)
ans = ans * i;
return (ans);
}
// function to count maximum length palindromes.
int numberOfPossiblePalindrome(string str, int n)
{
// Count number of occurrence
// of a charterer in the string
unordered_map<char, int> mp;
for (int i = 0; i < n; i++)
mp[str[i]]++;
int k = 0; // Count of singles
int num = 0; // numerator of result
int den = 1; // denominator of result
int fi;
for (auto it = mp.begin(); it != mp.end(); ++it)
{
// if frequency is even
// fi = ci / 2
if (it->second % 2 == 0)
fi = it->second / 2;
// if frequency is odd
// fi = ci - 1 / 2.
else
{
fi = (it->second - 1) / 2;
k++;
}
// sum of all frequencies
num = num + fi;
// product of factorial of
// every frequency
den = den * fact(fi);
}
// if all character are unique
// so there will be no palindrome,
// so if num != 0 then only we are
// finding the factorial
if (num != 0)
num = fact(num);
int ans = num / den;
if (k != 0)
{
// k are the single
// elements that can be
// placed in middle
ans = ans * k;
}
return (ans);
}
// Driver program
int main()
{
char str[] = "ababab";
int n = strlen(str);
cout << numberOfPossiblePalindrome(str, n);
return 0;
}
Java
// Java implementation for counting
// maximum length palindromes
import java.util.*;
class GFG
{
// factorial of a number
static int fact(int n)
{
int ans = 1;
for (int i = 1; i <= n; i++)
ans = ans * i;
return (ans);
}
// function to count maximum length palindromes.
static int numberOfPossiblePalindrome(String str, int n)
{
// Count number of occurrence
// of a charterer in the string
Map<Character,Integer> mp = new HashMap<>();
for (int i = 0; i < n; i++)
mp.put( str.charAt(i),mp.get( str.charAt(i))==null?
1:mp.get( str.charAt(i))+1);
int k = 0; // Count of singles
int num = 0; // numerator of result
int den = 1; // denominator of result
int fi;
for (Map.Entry<Character,Integer> it : mp.entrySet())
{
// if frequency is even
// fi = ci / 2
if (it.getValue() % 2 == 0)
fi = it.getValue() / 2;
// if frequency is odd
// fi = ci - 1 / 2.
else
{
fi = (it.getValue() - 1) / 2;
k++;
}
// sum of all frequencies
num = num + fi;
// product of factorial of
// every frequency
den = den * fact(fi);
}
// if all character are unique
// so there will be no palindrome,
// so if num != 0 then only we are
// finding the factorial
if (num != 0)
num = fact(num);
int ans = num / den;
if (k != 0)
{
// k are the single
// elements that can be
// placed in middle
ans = ans * k;
}
return (ans);
}
// Driver code
public static void main(String[] args)
{
String str = "ababab";
int n = str.length();
System.out.println(numberOfPossiblePalindrome(str, n));
}
}
// This code is contributed by Princi Singh
Python3
# Python3 implementation for counting
# maximum length palindromes
import math as mt
# factorial of a number
def fact(n):
ans = 1
for i in range(1, n + 1):
ans = ans * i
return (ans)
# function to count maximum length palindromes.
def numberOfPossiblePalindrome(string, n):
# Count number of occurrence
# of a charterer in the string
mp = dict()
for i in range(n):
if string[i] in mp.keys():
mp[string[i]] += 1
else:
mp[string[i]] = 1
k = 0 # Count of singles
num = 0 # numerator of result
den = 1 # denominator of result
fi = 0
for it in mp:
# if frequency is even
# fi = ci / 2
if (mp[it] % 2 == 0):
fi = mp[it] // 2
# if frequency is odd
# fi = ci - 1 / 2.
else:
fi = (mp[it] - 1) // 2
k += 1
# sum of all frequencies
num = num + fi
# product of factorial of
# every frequency
den = den * fact(fi)
# if all character are unique
# so there will be no palindrome,
# so if num != 0 then only we are
# finding the factorial
if (num != 0):
num = fact(num)
ans = num //den
if (k != 0):
# k are the single
# elements that can be
# placed in middle
ans = ans * k
return (ans)
# Driver Code
string = "ababab"
n = len(string)
print(numberOfPossiblePalindrome(string, n))
# This code is contributed by
# Mohit kumar 29
C#
// C# implementation for counting
// maximum length palindromes
using System;
using System.Collections.Generic;
class GFG
{
// factorial of a number
static int fact(int n)
{
int ans = 1;
for (int i = 1; i <= n; i++)
ans = ans * i;
return (ans);
}
// function to count maximum length palindromes.
static int numberOfPossiblePalindrome(String str, int n)
{
// Count number of occurrence
// of a charterer in the string
Dictionary<char,int> mp = new Dictionary<char,int>();
for (int i = 0 ; i < n; i++)
{
if(mp.ContainsKey(str[i]))
{
var val = mp[str[i]];
mp.Remove(str[i]);
mp.Add(str[i], val + 1);
}
else
{
mp.Add(str[i], 1);
}
}
int k = 0; // Count of singles
int num = 0; // numerator of result
int den = 1; // denominator of result
int fi;
foreach(KeyValuePair<char, int> it in mp)
{
// if frequency is even
// fi = ci / 2
if (it.Value % 2 == 0)
fi = it.Value / 2;
// if frequency is odd
// fi = ci - 1 / 2.
else
{
fi = (it.Value - 1) / 2;
k++;
}
// sum of all frequencies
num = num + fi;
// product of factorial of
// every frequency
den = den * fact(fi);
}
// if all character are unique
// so there will be no palindrome,
// so if num != 0 then only we are
// finding the factorial
if (num != 0)
num = fact(num);
int ans = num / den;
if (k != 0)
{
// k are the single
// elements that can be
// placed in middle
ans = ans * k;
}
return (ans);
}
// Driver code
public static void Main(String[] args)
{
String str = "ababab";
int n = str.Length;
Console.WriteLine(numberOfPossiblePalindrome(str, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation for counting
// maximum length palindromes
// factorial of a number
function fact(n)
{
let ans = 1;
for (let i = 1; i <= n; i++)
ans = ans * i;
return (ans);
}
// function to count maximum length palindromes.
function numberOfPossiblePalindrome(str,n)
{
// Count number of occurrence
// of a charterer in the string
let mp = new Map();
for (let i = 0; i < n; i++)
mp.set( str[i],mp.get( str[i])==null?
1:mp.get( str[i])+1);
let k = 0; // Count of singles
let num = 0; // numerator of result
let den = 1; // denominator of result
let fi;
for (let [key, value] of mp.entries())
{
// if frequency is even
// fi = ci / 2
if (value % 2 == 0)
fi = value / 2;
// if frequency is odd
// fi = ci - 1 / 2.
else
{
fi = (value - 1) / 2;
k++;
}
// sum of all frequencies
num = num + fi;
// product of factorial of
// every frequency
den = den * fact(fi);
}
// if all character are unique
// so there will be no palindrome,
// so if num != 0 then only we are
// finding the factorial
if (num != 0)
num = fact(num);
let ans = Math.floor(num / den);
if (k != 0)
{
// k are the single
// elements that can be
// placed in middle
ans = ans * k;
}
return (ans);
}
// Driver code
let str = "ababab";
let n = str.length;
document.write(numberOfPossiblePalindrome(str, n));
// This code is contributed by unknown2108
</script>
Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(n)
Similar Reads
Palindrome String Coding Problems
A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Palindrome String
Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome
Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read