1446. Anagram Dictionary Rank

Medium3.5 points estimatedCombinatoricsStringCountingMaths

A puzzle magazine prints, for each secret word, a dictionary of every distinct rearrangement of its letters, listed in ordinary alphabetical order with no repeats. Readers are asked where their own word sits in that dictionary.

Given word, return its 1-based position among all distinct rearrangements of its letters sorted lexicographically, modulo 1000000007. For instance "aab" has the rearrangements aab, aba, baa, so "aba" is at position 2. The list is astronomically long, so count instead: at each position, add the arrangements that start with a smaller still-unused letter, using factorials and modular inverses. Intended time is O(26 * n) with O(n) space.

Example 1

Input:
word = "aba"
Output:
2
Explanation:

The rearrangements of aab in order are aab, aba, baa, so aba is at position 2.

Example 2

Input:
word = "cab"
Output:
5
Explanation:

The six rearrangements are abc, acb, bac, bca, cab, cba, so cab is at position 5.

Example 3

Input:
word = "a"
Output:
1
Explanation:

A single letter has exactly one rearrangement, so its position is 1.

Constraints

1 ≤ word.length ≤ 105

word contains only lowercase letters a-z.

Answer modulo 1000000007. Products of residues exceed 253, so use BigInt or a split multiplication in JavaScript.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(26 * n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…