### PROBLEM LINK:

**Author:** Vineet Paliwal

**Tester:** Roman Rubanenko

**Editorialist:** Jingbo Shang

### DIFFICULTY:

CAKEWALK

### PREREQUISITES:

Factorial, Enumeration, Bruteforce

### PROBLEM:

Given a number with D digits, find the its rank in the ascendingly sorted list of all numbers that can be generated by permuting its digits.

### EXPLANATION:

Using the brute force enumeration, we can simply try all D! permutations and get the order. But it takes too much time.

Let’s consider a simpler problem: how many different numbers (leading 0s are fine) can we get by permuting its digits? Suppose the number of digit i (0 <= i <= 9) is N[i]. Then, the answer is

In another word, the target of the original problem is to find how many numbers generated by permuting the input number’s digits are smaller than it.

The smaller numbers can be grouped by how long the common prefix with the input number they have. Considering the smaller numbers with L digits same prefix, enumerate the next digit (must be smaller than the input number’s next digit) and sum the number of “how many different numbers can we get by permuting the remaining digits” which is solved previously.

The final algorithm is as follow:

For L = D - 1 downto 0

For nextDigit = 0 to inputNumer[L + 1]

Answer += “how many different numbers can we get by permuting the remaining digits”

64-bit integers are enough for answers. Thus, the time complexity is about O(D).

### AUTHOR’S AND TESTER’S SOLUTIONS:

Author’s solution can be found here.

Tester’s solution can be found here.