Talentd
FleetCode

3109. Find the Index of Permutation

Medium37.1% acceptancePremium elsewhere, free here

Given an array perm of length n which is a permutation of [1, 2, ..., n], return the index of perm in the lexicographically sorted array of all of the permutations of [1, 2, ..., n].

Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: perm = [1,2]

Output: 0

Explanation:

There are only two permutations in the following order:

[1,2], [2,1]

And [1,2] is at index 0.

Example 2:

Input: perm = [3,1,2]

Output: 4

Explanation:

There are only six permutations in the following order:

[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]

And [3,1,2] is at index 4.

Constraints:

  • 1 <= n == perm.length <= 105
  • perm is a permutation of [1, 2, ..., n].

Hints open one at a time

Hint 1
If perm[0] is x, there are at least (x - 1) * (n - 1)! permutations before perm. (All the ones starting with numbers less than x)
Hint 2
Can you find out what happens for perm[1] onwards?
Hint 3
Think about the count of the numbers that can be in place of perm[i] and come before it.
12:31
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[1,2]
Input
[3,1,2]
Your code is saved on this device.Solution