Ctrl K

Rank of an Arrangement

Medium
The array order of length n is an arrangement of the numbers 1 to n: each appears exactly once. Write out all n! arrangements of these numbers in lexicographic (dictionary) order and number them from zero. Return the position of order in that list. The position can be huge, so return it modulo 10⁹ + 7.
Example 1
order=[2, 3, 1] → 3

In order: [1,2,3], [1,3,2], [2,1,3], [2,3,1], ... so ours sits at position 3.

Example 2
order=[1] → 0

There is only one arrangement of a single number, at position 0.

Example 3
order=[4, 1, 2, 3] → 18

All 3 · 3! = 18 arrangements starting with 1, 2 or 3 come before it, and it is the first of those starting with 4.

Constraints
  • 1 ≤ n ≤ 10⁵
  • order contains every number from 1 to n exactly once
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOnes Outnumber Zeros MediumSmaller Values to the Right HardWindow Sums Within a Band HardPairs With a Steep Drop HardCost of Filling a Sorted Shelf Hard
loading Python…
Input
order=[2, 3, 1]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 100 tests on the server, hidden ones included.