Sorted Permutation Rank with Repeats
Last updated
Last updated
Given a string, find the rank of the string amongst its permutations sorted lexicographically. Note that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations. Look at the example for more details.
Example :
The answer might not fit in an integer, so return your answer % 1000003
NOTE: 1000003 is a prime number NOTE: Assume the number of characters in string < 1000003
Explaination:
Letβs look at the string βsettLeβ. It has repetition(2 βeβ and 2 βtβ) as well as upper case letter(βLβ). Total 6 characters and total number of permutations are 6!/(2!*2!). Now there are 3 characters(2 βeβ and 1 βLβ) on the right side of βsβ which come before βsβ lexicographically. If there were no repetition then there would be 3*5! smaller strings which have the first character less than βsβ. But starting from position 0, till end there are 2 βsβ and 2 βt'(i.e. repetations). Hence number of possible smaller permutations with first letter smaller than βsβ are (3*5!)/(2!*2!). Similarly if we fix βsβ and look at the letters from index 1 to end then there is 1 character(βLβ) lexicographically less than βeβ. And starting from position 1 there are 2 repeated characters(2 βeβ and 2 βtβ). Hence number of possible smaller permutations with first letter βsβ and second letter smaller than βeβ are (1*4!)/(2!*2!).
Similarly we can form the following table: