Find the Rank

2.7

16 votes
Medium
Problem

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.

The answer might not fit in an integer, so return your answer % 1000003

Assume the number of characters in string < 1000003 1<=n <= 100

Input format:

In the first line take the input n. Next n lines contain the string.

Output Format:

Print the rank for each string in each line.

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Example :

Input :

1

'aba'

Output :

2

The order permutations with letters 'a', 'a', and 'b' :

aab

aba

baa

Editor Image

?