algorithmstring-algorithm

Rank of string solution


I was going through a question where it asks you to find the rank of the string amongst its permutations sorted lexicographically.

O(N^2) is pretty clear.

Some websites have O(n) solution also. The part that is optimized is basically pre-populating a count array such that

count[i] contains count of characters which are present in str and are smaller than i.

I understand that this'd reduce the complexity but can't fit my head around how we are calculating this array. This is the function that does this (taken from the link):

// Construct a count array where value at every index
// contains count of smaller characters in whole string
void populateAndIncreaseCount (int* count, char* str)
{
    int i;

    for( i = 0; str[i]; ++i )
        ++count[ str[i] ];

    for( i = 1; i < 256; ++i )
        count[i] += count[i-1];
}

Can someone please provide an intuitive explanation of this function?


Solution

  • Understood after going through it again. Got confused due to wrong syntax in c++. It's actually doing a pretty simple thing (Here's the java version :

    void populateAndIncreaseCount(int[] count, String str) {
        // count is initialized to zero for all indices
        for (int i = 0; i < str.length(); ++i) {
          count[str.charAt(i)]++;
        }
    
        for (int i = 1; i < 256; ++i)
          count[i] += count[i - 1];
      } 
    

    After first step, indices whose character are present in string are non-zero. Then, for each index in count array, it'd be the sum of all the counts till index-1 since array represents lexicographically sorted characters. And, after each search, we udate the count array also:

    // Removes a character ch from count[] array // constructed by populateAndIncreaseCount()

    void updatecount (int* count, char ch)
    {
        int i;
        for( i = ch; i < MAX_CHAR; ++i )
            --count[i];
    }