Short Palindrome


Problem Statement :


Consider a string, , of  lowercase English letters where each character,  (, denotes the letter at index  in . We define an  palindromic tuple of  to be a sequence of indices in  satisfying the following criteria:

, meaning the characters located at indices  and  are the same.
, meaning the characters located at indices  and  are the same.
, meaning that , , , and  are ascending in value and are valid indices within string .
Given , find and print the number of  tuples satisfying the above conditions. As this value can be quite large, print it modulo .


unction Description
Complete the function shortPalindrome in the editor below.

shortPalindrome has the following paramter(s):
- string s: a string

Returns
- int: the number of tuples, modulo 

Input Format

A single string, .

Constraints

It is guaranteed that  only contains lowercase English letters.



Solution :



title-img


                            Solution in C :

In   C  :








#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

char s[1000000] = "hello";
int n = 0;
long long* map[26];
int maxLen = 0;
long long* work;
long long* psum;
long long* ssum;
long long* rsum;
const long long modul = 1000000007;

long long calc(int len);
long long* getArr(char c);
void solve(long long* c1, long long* c2);
long long solveOne(long long l);

int main(int argc, char* argv[]) {
    char c = ' ';
    for (int i = 0; i <= 1000005; ++i) {
        c = getchar();
        if (('\n' == c) || (EOF == c)) {
            s[i] = '\0';
            n = i;
            break;
        } else {
            s[i] = c - 'a';
        }
    }
    
    for (char c = 0; c < 26; ++c) {
        map[c] = getArr(c);
	//printf("%lld\n", map[c][0]);
        if (map[c][0] > maxLen)
            maxLen = map[c][0];
    }
    
    work = malloc((maxLen + 1) * sizeof(long long));
    psum = malloc((maxLen + 1) * sizeof(long long));
    ssum = malloc((maxLen + 1) * sizeof(long long));
    rsum = malloc((maxLen + 1) * sizeof(long long));
    
    long long ans = 0;
    for (char c1 = 0; c1 < 26; ++c1) {
        for (char c2 = 0; c2 < 26; ++c2) {
            if (c1 == c2) {
                if (map[c1][0] > 0) {
                    //printf("%d\n", map[c1][0]);
                    long long t = solveOne(map[c1][0]);
                    ans = (ans + t) % modul;
                }
            } else {
                if ((map[c1][0] > 0) && (map[c2][0] > 0)) {
                    solve(map[c1], map[c2]);
                    //for (int i = 0; i < map[c1][0] + 1; ++i) printf("%d ", work[i]);
                    //printf("\n");
                    ans += calc(map[c1][0] + 1);
                    ans = ans % modul;
                }
            }
        }
    }
    
    printf("%lld\n", ans);
    return 0;
}

long long solveOne(long long l) {
    long long res = 0;
    for (long long i = 1; i <= (l - 3); ++i) {
        res += (i * (l - 2 - i) * (l - 1 - i) / 2) % modul;
	res = res % modul;
    }
    res = res % modul;
    return res;
}

long long calc(int len) {
    psum[0] = work[0];
    //printf("psum: %d ", psum[0]);
    for (int i = 1; i < len; ++i) {
        psum[i] = psum[i - 1] + work[i];
        //printf("%d ", psum[i]);
    }
    ssum[0] = psum[0];
    //printf("\nssum: %d ", ssum[0]);
    for (int i = 1; i < len; ++i) {
        ssum[i] = (ssum[i - 1] + psum[i]) % modul;
        //printf("%d ", ssum[i]);
    }
    rsum[len - 1] = work[len - 1];
    for (int i = len - 2; i >= 0; --i) {
        rsum[i] = rsum[i + 1] + work[i];
    }
    /*(printf("\nrsum: ");
    for (int i = 0; i < len; ++i) {
        printf("%d ", rsum[i]);
    }
    printf("\n");*/
    long long res = 0;
    for (int i = 2; i < len; ++i) {
        res += (rsum[i] * ssum[i - 2]) % modul;
    }
    res = res % modul;
    return res;
}

void solve(long long* c1, long long* c2) {
    long long l1 = 1;
    long long l2 = 1;
    long long r = 0;
    long long count = 0;
    for (;;) {
        if ((l1 > c1[0]) && (l2 > c2[0])) {
            work[r] = count;
            ++r;
            break;
        } else if (l1 > c1[0]) {
            ++l2;
            ++count;
        } else if (l2 > c2[0]) {
            ++l1;
            work[r] = count;
            count = 0;
            ++r;
        } else if (c1[l1] > c2[l2]) {
            ++l2;
            ++count;
        } else if (c1[l1] < c2[l2]) {
            ++l1;
            work[r] = count;
            count = 0;
            ++r;
        }
    }
}

long long* getArr(char c) {
    long long count = 0;
    for (long long i = 0; i < n; ++i)
        if (c == s[i])
            ++count;
        
    long long *res = malloc(sizeof(long long) * (count + 1));
    long long cur = 1;
    res[0] = count;
    for (long long i = 0; i < n; ++i)
        if (c == s[i])
            res[cur++] = i;
    
    return res;
}
                        


                        Solution in C++ :

In  C++  :







#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define fre 	freopen("0.in","r",stdin);freopen("0.out","w",stdout)
#define abs(x) ((x)>0?(x):-(x))
#define MOD 1000000007
#define LL signed long long int
#define scan(x) scanf("%d",&x)
#define print(x) printf("%d\n",x)
#define scanll(x) scanf("%lld",&x)
#define printll(x) printf("%lld\n",x)
#define rep(i,from,to) for(int i=(from);i <= (to); ++i)
#define pii pair<int,int>

vector<int> G[2*100000+5];
LL suf[654];
LL pre[654];
LL dp[29][29];

int main(){
	//fre;
	string S;
	cin>>S;
	int N = S.size();
	LL ans = 0;
	S = " " + S;
	for(int i=1;i<=N;++i)suf[S[i]-'a'+1]++;
	for(int i=1;i<=N;++i){
		int x = S[i]-'a'+1;
		suf[x]--;
		for(int j=1;j<=26;++j){
			ans += dp[j][x] * suf[j];
			ans %= MOD;
		}
		for(int j=1;j<=26;++j){
			dp[j][x] += pre[j];
		}
		pre[x]++;
	}
	cout<<ans;
}
                    


                        Solution in Java :

In   Java  :








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

public class Solution {

    public static void main(String[] args) throws Exception{
BufferedReader inR = new BufferedReader(new InputStreamReader(System.in));
        String s = inR.readLine().trim();
        long MOD = 1000000000L+7;
        long[] cnt = new long[26];
        long[][] sumK = new long[26][26];
        long[][] delta = new long[26][26];
        long ans = 0;
        for(int i=0; i<s.length(); i++) {
            int c = s.charAt(i) - 'a';
            for(int j=0; j<26; j++) {
                ans = (ans + delta[c][j]) % MOD;
            }
            
            for(int j=0; j<26; j++) {
                delta[j][c] = (delta[j][c] + sumK[j][c]) % MOD;
                sumK[j][c] = (sumK[j][c] + cnt[j]) % MOD;
            }
            
            cnt[c] += 1;
        }
        System.out.println(ans % MOD);
        inR.close();
    }
}
                    


                        Solution in Python : 
                            
In   Python3 :







#!/bin/python3

import math
import os
import random
import re
import sys
import collections

# Complete the shortPalindrome function below.
def shortPalindrome(s):
    arr1 = [0]*26
    arr2 = [[0]*26 for i in range(26)]
    arr3 = [0]*26
    ans = 0
    for i in range(len(s)):
        idx = ord(s[i]) - ord('a')
        ans += arr3[idx]
        for j in range(26):
            arr3[j] += arr2[j][idx]
        for j in range(26):
            arr2[j][idx] += arr1[j]
        arr1[idx] += 1
    return ans % (10**9+7)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = shortPalindrome(s)

    fptr.write(str(result) + '\n')

    fptr.close()
                    


View More Similar Problems

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →