PLSTR - Editorial

PROBLEM LINK:

Practice
Contest

Author: Ayush Nagal

DIFFICULTY:

MEDIUM

PREREQUISITES:

Math

PROBLEM:

Given a string S, find the rank of the string amongst its permutations sorted lexicographically.
Assume that no characters are repeated.

EXPLANATION:

It is a well-known problem of Permutation and Combination. First of all, we need an auxiliary array (like Counting Sort) to store the frequency of all the characters in the given string. It can be obtained as follows:

map <char,int> m;
map <char,int>::iterator it;

for(i=0;i < n;i++){
    m[B*] = i;
}

After obtaining the auxiliary array, we can use the following code to obtain the rank:

while(fix < n)
{
    r = m[A[fix]];
    ans = ans + ((r)*fact(n-1-fix))%mod;
    if(ans > mod)
    ans = ans - mod;

    for(it=m.begin();it!=m.end();it++)
    {
        if((*it).first>A[fix])
        {
            (*it).second -= 1;
        }
    }
    fix++;
}

The rank will be ans+1.

AUTHOR’S SOLUTION:

Author’s solution can be found here.