HackerRank Maximum Palindromes Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Maximum Palindromes Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Maximum Palindromes Solution
HackerRank Maximum Palindromes Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Maximum Palindromes

Task

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 q days, she would select two integers l and r, take the substring s1 . . . r (the substring of s from index l to index r), and ask the following question:

Consider all the palindromes that can be constructed from some of the letters from s1 . . . 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 = madamimadaml = 4 and r = 7, then we have,

image

Your job as the head of the marketing team is to answer all the queries

Complete the functions initialize and answerQuery and return the number of maximumlength palindromes modulo 109 + 7.

Input Format

The first line contains the string s.

The second line contains a single integer q.

The ith of the next q lines contains two space-separated integers li , ri  denoting the l and r values Anna selected on the ith day.

Constraints

Here, |s| denotes the length of s.

  • 1 <= |s| <= 105
  • 1 <= q <= 105
  • 1 <= li <= ri <= |s|

Subtasks

For 30% of the total score:

  • 1 <= |s| <= 100
  • 1 <= q <= 1000
  • ri – li <= 3

For 60% of the total score:

  • 1 <= |s| <= 100
  • 1 <= q <= 1000

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, l = 2 and r = 3. The maximum-length palindrome is “ee”.

image

Sample Input 1

abab
1
1 4

Sample Output 1

2

Explanation 1

Here, the maximum-length palindromes are “abbaand “baab”.

HackerRank Maximum Palindromes Solution

Maximum Palindromes Solution in C

#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 Solution in Cpp

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int mod = 1000000007;
const int Maxn = 100005;
const int Maxl = 26;

int fac[Maxn], inv[Maxn];
int freq[Maxn][Maxl];

int Inv(int x)
{
    int res = 1;
    int p = mod - 2;
    while (p) {
        if (p & 1) res = ll(res) * x % mod;
        p >>= 1; x = ll(x) * x % mod;
    }
    return res;
}

int C(int n, int k)
{
    if (n < 0 || k < 0 || k > n) return 0;
    return ll(fac[n]) * inv[k] % mod * inv[n - k] % mod;
}

void initialize(string s) {
    for (int i = 1; i <= s.length(); i++) {
        for (int j = 0; j < Maxl; j++)
            freq[i][j] = freq[i - 1][j];
        freq[i][s[i - 1] - 'a']++;
    }
}

int answerQuery(int l, int r) {
    int odd = 0, tot = 0;
    for (int i = 0; i < Maxl; i++) {
        tot += (freq[r][i] - freq[l - 1][i]) / 2;
        odd += (freq[r][i] - freq[l - 1][i]) % 2;
    }
    int res = 1;
    if (odd > 0) res = ll(res) * odd % mod;
    for (int i = 0; i < Maxl; i++) {
        int my = (freq[r][i] - freq[l - 1][i]) / 2;
        res = ll(res) * C(tot, my) % mod; tot -= my;
    }
    return res;
}

int main() {
    fac[0] = inv[0] = 1;
    for (int i = 1; i < Maxn; i++) {
        fac[i] = ll(fac[i - 1]) * i % mod;
        inv[i] = Inv(fac[i]);
    }
    string s;
    cin >> s;
    initialize(s);
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        int l;
        int r;
        cin >> l >> r;
        int result = answerQuery(l, r);
        cout << result << endl;
    }
    return 0;
}

Maximum Palindromes Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int R = 26;
    static int n;
    static int[][] csum;
    static long[] fac;
    static long[] ifac;
    static long MOD = 1000000007;
    static void initialize(String s) {
        // This function is called once before all queries.
        csum = new int[R][n+1];
        for (int i = 1; i <= n; i++) {
            int id = s.charAt(i-1) - 'a';
            for (int j = 0; j < R; j++)
                csum[j][i] = csum[j][i-1];
            csum[id][i] = csum[id][i-1] + 1;
        }
        
        fac = new long[n+1];
        ifac = new long[n+1];
        fac[0] = 1;
        ifac[0] = 1;
        for (int i = 1; i <= n; i++) {
            fac[i] = fac[i-1] * i % MOD;
            ifac[i] = ifac[i-1] * inv(i, MOD) % MOD;
        }
    }
    
    static private long inv(long v, long m) {
        return (extendedGCD(v, m)[0] % m + m) % m;
    }
    
    static private long[] extendedGCD(long x, long y) {
        long[] ans = new long[3];
        if (y == 0) {
            ans[0] = 1;
            ans[2] = x;
            return ans;
        }
        
        long q = x / y;
        long r = x % y;
        long[] t = extendedGCD(y, r);
        ans[0] = t[1];
        ans[2] = t[2];
        ans[1] = t[0] - ans[0] * q;
        return ans;
    }

    static int answerQuery(int l, int r) {
        // Return the answer for this query modulo 1000000007.
        int nmid = 0;
        int nside = 0;
        long ans = 1;
        for (int i = 0; i < R; i++) {
            int cnt = csum[i][r] - csum[i][l-1];
            int left = cnt / 2;
            nside += left;
            ans = ans * ifac[left] % MOD;
            if (cnt % 2 == 1) 
                nmid++;            
        }
        ans = ans * fac[nside] % MOD;
        if (nmid > 1)
            ans = ans * nmid % MOD;
        return (int)ans;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
        n = s.length();
        initialize(s);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int l = in.nextInt();
            int r = in.nextInt();
            int result = answerQuery(l, r);
            System.out.println(result);
        }
        in.close();
    }
}

Maximum Palindromes Solution in Python

#!/bin/python

import sys
mod = (10**9)+7
fact = []
infact =[]
S = []
def exp(a,b,mod):
    ans = 1
    while(b!=0):
        if((b%2)== 1):
            ans = (ans*a)%mod
        a = (a*a)%mod
        b>>=1
    return ans
def initialize(s):
    # This function is called once before all queries.
    global mod,fact,infact,S
    fact = [1]*((10**5) +1)
    for i in xrange(1,(10**5) + 1):
        fact[i]= (i*fact[i-1])%mod
    infact = [0]*((10**5) +1)
    infact[-1]= exp(fact[-1],mod-2,mod)
    for i in xrange((10**5)-1,-1,-1):
        infact[i] = ((i+1)*infact[i+1])%mod
    l = len(s)
    for i in s:
        S += [[0]*26]
        S[-1][ord(i)-97]=1
    for i in xrange(1,l):
        for j in xrange(26):
            S[i][j]+=S[i-1][j]
def answerQuery(s,l, r):
    global mod
    temp = [0]*26
    for i in xrange(26):
        temp[i]=S[r][i]-S[l][i]
    temp[ord(s[l])-97]+=1
    tot = 0
    one = 0
    ans = 1
    for i in temp:
        one += i%2
        tot += i/2
        ans = (ans*infact[i/2])%mod
    ans = (ans*fact[tot])%mod
    if(one!=0):
        ans = (ans * one)%mod
    return ans
if __name__ == "__main__":
    s = raw_input().strip()
    initialize(s)
    q = int(raw_input().strip())
    for a0 in xrange(q):
        l, r = raw_input().strip().split(' ')
        l, r = [int(l), int(r)]
        result = answerQuery(s,l-1, r-1)
        print result

Maximum Palindromes Solution using JavaScript

Maximum Palindromes Solution in Scala

Maximum Palindromes Solution in Pascal

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.

Disclaimer: This problem (Maximum Palindromes) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment