![HackerRank Maximum Palindromes Problem Solution](https://thecscience.com/wp-content/uploads/2023/04/HackerRank-Maximum-Palindromes-Problem-Solution.jpg)
HackerRank Maximum Palindromes Solution
In this post, we will solve HackerRank Maximum Palindromes Problem Solution.
Madam Hannah Otto, the CEO of Reviver Corp., is fond of palindromes, or words that read the same forwards or backwards. She thinks palindromic brand names are appealing to millennials.
As part of the marketing campaign for the company’s new juicer called the Rotator™, Hannah decided to push the marketing team’s palindrome-searching skills to a new level with a new challenge.
In this challenge, Hannah provides a string s consisting of lowercase English letters. Every
day, for a days, she would select two integers land r, take the substring s…r (the substring of s from index to index r), and ask the following question: Consider all the palindromes that can be constructed from some of the letters from $1…r. You can reorder the letters as you need. Some of these palindromes have the maximum length among all these palindromes. How many maximum-length palindromes are there? For example, if s = madamimadam, 14 and r = 7, then we have
Your job as the head of the marketing team is to answer all the queries. Since the answers can be very large, you are only required to find the answer modulo 109 + 7. Complete the functions initialize and answerQuery and return the number of maximum-length palindromes modulo 109 +7.
Input Format
The first line contains the string s.
The second line contains a single integer q.
The ¿th of the next a lines contains two space-separated integers l₂, r; denoting the land r values Anna selected on the ¿th day.
Output Format
For each query, print a single line containing a single integer denoting the answer.
Sample Input 0
week 2 1 4 2 3
Sample Output 0
2 1
Explanation 0
On the first day, l = 1 and r = 4. The maximum-length palindromes are “ewe” and “eke”.
On the second day, I = 2 and r = 3. The maximum-length palindrome is “ee”.
Sample Input 1
abab 1 1 4
Sample Output 1
2
Explanation 1
Here, the maximum-length palindromes are “abba” and “baab”.
![HackerRank Maximum Palindromes Problem Solution](https://thecscience.com/wp-content/uploads/2023/04/HackerRank-Maximum-Palindromes-Problem-Solution-1024x576.jpg)
Maximum Palindromes C Solution
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#define MOD 1000000007
#define MAX 100000
#define MAXP 100000
int a[MAX+1][26];
long fact[MAX+1];
void initialize(char* s) {
for(int j=0; j<26; j++) {
a[0][j] = 0;
}
for(int i=0; s[i]; i++) {
for(int j=0; j<26; j++) {
a[i+1][j] = a[i][j];
}
a[i+1][s[i]-'a'] ++;
/*for(int j=0; j<26; j++) {
printf("a[until(inc) %c][for %c] = %d\n", s[i], j+'a', a[i+1][j]);
}*/
}
fact[0] = 1L;
for(int i=0; s[i]; i++) {
fact[i+1] = (fact[i]*(i+1))%MOD;
}
}
long dinv(long x) {
int i;
static long r[MAXP], s[MAXP], t[MAXP], q[MAXP];
r[0] = MOD; r[1] = x;
s[0] = 1; s[1] = 0;
t[0] = 0; t[1] = 1;
i = 1;
while(r[i] > 0) {
q[i] = r[i-1]/r[i];
r[i+1] = r[i-1] - q[i]*r[i];
s[i+1] = s[i-1] - q[i]*s[i];
t[i+1] = t[i-1] - q[i]*t[i];
//printf("%ld %ld %ld\n", r[i+1], s[i+1], t[i+1]);
i ++;
}
return (t[i-1]+MOD)%MOD;
}
int answerQuery(char* s, int l, int r) {
int v[26];
long res;
for(int i=0; i<26; i++) {
v[i] = a[r][i] - a[l-1][i];
}
/*for(int i=0; i<26; i++) {
printf("v[%c] = %d\n", i+'a', v[i]);
}
printf("\n");*/
int oddcount = 0;
int eventotal = 0;
for(int i=0; i<26; i++) {
oddcount += v[i]%2;
eventotal += v[i]/2;
}
res = fact[eventotal];
if(oddcount > 0) {
res = (res*oddcount)%MOD;
}
for(int i=0; i<26; i++) {
if(v[i]/2 > 0) {
res = (res*dinv(fact[v[i]/2]))%MOD;
}
}
return (int)res;
}
int main() {
char* s = (char *)malloc(512000 * sizeof(char));
scanf("%s", s);
initialize(s);
int q;
scanf("%i", &q);
for(int a0 = 0; a0 < q; a0++){
int l;
int r;
scanf("%i %i", &l, &r);
int result = answerQuery(s, l, r);
printf("%d\n", result);
}
return 0;
}
Maximum Palindromes C++ Solution
#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL M = (LL)(1e9+7);
string str;
int st[3*100009][26];
int alpha[26];
LL fact[100009];
void build(int s,int e,int idx){
if(s>e){return ;}
if(s==e){
st[idx][str[s]-'a']++;
//cout<<idx<<""<<s<<","<<e<<endl;
return ;
}
int m = (s+e)/2;
build(s,m,2*idx+1);
build(m+1,e,2*idx+2);
//cout<<idx<<""<<s<<","<<e<<endl;
for(int i=0;i<26;i++){
st[idx][i]+=(st[2*idx+1][i] + st[2*idx+2][i]);
}
}
void query(int s,int e,int l,int r,int idx){
if(s>e || s>r || l>e){return ;}
if(l<=s && r>=e){
for(int i=0;i<26;i++){
alpha[i]+=st[idx][i];
}
return ;
}
int m=(s+e)/2;
query(s,m,l,r,2*idx+1);
query(m+1,e,l,r,2*idx+2);
}
LL modinv(LL a,LL m){
LL m0 = m, t, q;
LL x0 = 0, x1 = 1;
if (m == 1)
return 0;
while (a > 1)
{
// q is quotient
q = a / m;
t = m;
// m is remainder now, process same as
// Euclid's algo
m = a % m, a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
int main(){
fact[0]=1;
for(int i=1;i<100009;i++){
fact[i] = (fact[i-1]*i)%M;
}
cin>>str;
int n = (int)str.length();
// cout<<n<<endl;
build(0,n-1,0);
int q;
cin>>q;
while(q--){
int l,r;
cin>>l>>r;
memset(alpha,0,sizeof(alpha));
query(0,n-1,l-1,r-1,0);
LL ans=1;
int x=0;
LL y=0;
for(int i=0;i<26;i++){
x += (alpha[i] - alpha[i]%2);
y = y + (LL)(alpha[i]%2);
}
//cout<<x<<" "<<y<<endl;
ans = fact[x/2];
for(int i=0;i<26;i++){
ans = (ans * modinv(fact[(alpha[i] - alpha[i]%2)/2],M))%M;
}
if(y>0){ans = (ans*y)%M;}
cout<<ans<<endl;
}
}
Maximum Palindromes Java Solution
/**
* Created by Aminul on 1/2/2018.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Maximum_Palindromes {
static long fac[] = new long[(int)1e5+50], mod = (int)1e9+7;
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
fac[0] = 1;
for(int i = 1; i <= 1_00_000; i++){
fac[i] = (fac[i-1]*(long)i) % mod;
}
char [] s = (" "+in.next()).toCharArray();
int n = s.length;
N = (int)Math.sqrt(n);
int q = in.nextInt();
Node [] pair = new Node[q];
for(int i = 0; i < q; i++){
pair[i] = new Node(in.nextInt(), in.nextInt(), i);
}
Arrays.sort(pair);
long [] ans = new long[q];
int count[] = new int[26];
int l = 1, r = 0, res = 0, x = 0;
for(int i = 0; i < q; i++){
while( r < pair[i].v){
r++;x = s[r] - 'a';
count[x]++;
}
while( r > pair[i].v){
x = s[r] - 'a';
count[x]--;
r--;
}
while( l > pair[i].u){
l--;x = s[l] - 'a';
count[x]++;
}
while( l < pair[i].u) {
x = s[l] - 'a';
count[x]--;
l++;
}
//debug(pair[i].u, pair[i].v, max, cnt, " ", count);
ans[pair[i].idx] = getRes(count) % mod;
}
for(long i: ans) pw.println(i);
pw.close();
}
static long getRes(int [] count){
int max = 0, cnt = 0;
int length = 0;
long mult = 1;
for(int k : count){
if(k % 2 == 1){
cnt++;
}
length += k/2;
mult = (mult * fac[k/2]) % mod;
}
for(int k : count){
if(max > 0 && max == k) cnt++;
}
if(cnt == 0) cnt = 1;
long inv = modInverse(mult, mod);
//debug(length, max, cnt, mult, count);
//return ( ((fac[length] * inv) % mod) * (long) cnt) % mod;
return safeMultiply(fac[length], inv, cnt);
}
static long safeMultiply(long a, long b, long c){
return ((BigInteger.valueOf(a).multiply(BigInteger.valueOf(b).multiply(BigInteger.valueOf(c)))).mod(BigInteger.valueOf(mod))).longValue();
}
public static long mod(long a, long m) {
long A = (a % m);
return A >= 0 ? A : A + m;
}
public static long modInverse(long a, long m) {
return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(m)).longValue();
// a = mod(a, m);
// return a == 0 ? 0 : mod((1 - modInverse(m % a, a) * m) / a, m);
}
static int N;
static class Node implements Comparable<Node>{
public int u, v, idx;
public Node(int uu, int vv, int i){
u = uu; v = vv; idx = i;
}
public int compareTo(Node n){
if(u/N != n.u/N) return u - n.u;
else return v - n.v;
}
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is){
for(int i='0';i<='9';i++) ints[i]=i-'0';
this.is = is;
}
public int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = (num<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = (num<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
}
Maximum Palindromes Pascal Solution
uses math;
const base=round(1e9+7);
var s:ansistring; i,q,l,r:longint; cnt1,cnt2,cnt3:int64; c:char;
cnt:array[0..100000,'a'..'z']of int64;
factorial:array[0..100000]of int64;
function power(a,b:int64):int64;
begin
if b=0 then exit(1);
power:=power(a,b>>1);
power:=power*power mod base;
if odd(b) then power:=power*a mod base
end;
begin
read(s,q);
factorial[0]:=1;
for i:=1 to length(s) do
factorial[i]:=factorial[i-1]*i mod base;
for c:='a' to 'z' do
for i:=1 to length(s) do
cnt[i][c]:=cnt[i-1][c] + ord(s[i]=c);
for q:=1 to q do
begin
read(l,r);
cnt1:=0; cnt2:=0; cnt3:=1;
for c:='a' to 'z' do
begin
i:=cnt[r][c]-cnt[l-1][c];
cnt1:=cnt1+(i and 1);
cnt2:=(cnt2+i>>1) mod base;
cnt3:=cnt3*factorial[i>>1] mod base
end;
cnt1:=max(cnt1,1);
writeln((cnt1*factorial[cnt2] mod base)*power(cnt3,base-2) mod base)
end
end.
Maximum Palindromes Python Solution
from collections import defaultdict
from copy import copy
M = int(1e9) + 7
fact = [1]
for i in range(1,int(1e5) + 10):
fact.append(fact[-1]*i % M)
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
memo = {}
def modinv(a, m):
if a in memo:
return memo[a]
while a < 0:
a += m
g, x, y = egcd(a, m)
if g != 1:
raise Exception('Modular inverse does not exist')
else:
memo[a] = x%m
return x % m
s = input().strip()
occ = [defaultdict(int)]
for ch in s:
newd = copy(occ[-1])
newd[ch] += 1
occ.append(newd)
def query(l, r):
d = defaultdict(int)
for ch in occ[r]:
d[ch] += occ[r][ch]
for ch in occ[l-1]:
d[ch] -= occ[l-1][ch]
odds = 0
for k, v in copy(d).items():
if v&1:
odds += 1
d[k] = v - (v&1)
res = 1
total = 0
for k, v in d.items():
res *= modinv(fact[v//2], M)
total += v//2
res %= M
return (max(1, odds)*res*fact[total])%M
for _ in range(int(input())):
l, r = map(int, input().split())
print(query(l, r))
Other Solutions