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 permutations of [1, 2, ..., n].

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

Lexicographic order means dictionary order - for example, permutations of [1,2,3] in lexicographic order are: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].

Input & Output

Example 1 — Basic Case
$ Input: perm = [2,3,1]
Output: 3
💡 Note: All permutations of [1,2,3] in lexicographic order: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]. The permutation [2,3,1] is at index 3.
Example 2 — First Permutation
$ Input: perm = [1,2]
Output: 0
💡 Note: Permutations of [1,2] in order: [1,2], [2,1]. The permutation [1,2] is the first one, so index is 0.
Example 3 — Last Permutation
$ Input: perm = [3,2,1]
Output: 5
💡 Note: The permutation [3,2,1] is the last permutation of [1,2,3] in lexicographic order, so it's at index 5.

Constraints

  • 1 ≤ perm.length ≤ 1000
  • perm is a permutation of [1, 2, ..., n]

Visualization

Tap to expand
Find the Index of Permutation INPUT perm = [2, 3, 1] 2 idx 0 3 idx 1 1 idx 2 All Permutations (sorted): 0: [1,2,3] 1: [1,3,2] 2: [2,1,3] 3: [2,3,1] 4: [3,1,2] 5: [3,2,1] n = 3, Total: 3! = 6 MOD = 10^9 + 7 ALGORITHM STEPS 1 Count smaller elements For each position, count unused smaller numbers 2 Multiply by factorial count * (n-1-i)! Add to result 3 Process [2,3,1] i=0: perm[0]=2 smaller unused: {1} = 1 1 * 2! = 2 i=1: perm[1]=3 smaller unused: {1} = 1 1 * 1! = 1 4 Sum all contributions index = 2 + 1 + 0 = 3 Return 3 % (10^9+7) FINAL RESULT Permutation Index Found! Output: 3 Verification: Index 0: [1,2,3] Index 1: [1,3,2] Index 2: [2,1,3] Index 3: [2,3,1] -- OK Index 4: [3,1,2] Index 5: [3,2,1] [OK] Position confirmed! Key Insight: The index equals the sum of (count of smaller unused elements) * (remaining positions)! Use Fenwick Tree or segment tree for efficient counting. Time: O(n log n), Space: O(n) TutorialsPoint - Find the Index of Permutation | Optimal Solution
Asked in
Google 35 Microsoft 28 Amazon 22 Facebook 18
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen