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 Index of Permutation [2,3,1] in All Permutations of [1,2,3]All permutations in lexicographic order:[1,2,3]Index 0[1,3,2]Index 1[2,1,3]Index 2[2,3,1]Index 3[3,1,2]Index 4[3,2,1]Index 5Mathematical calculation:Position 0: 1 number smaller than 2 → 1 × 2! = 2Position 1: 1 number smaller than 3 → 1 × 1! = 1Position 2: 0 numbers smaller than 1 → 0 × 0! = 0Result: 2 + 1 + 0 = 3
Understanding the Visualization
1
Input
Given permutation [2,3,1] of [1,2,3]
2
Process
Calculate position using factorial mathematics
3
Output
Return lexicographic index: 3
Key Takeaway
🎯 Key Insight: Use factorial mathematics to count permutations lexicographically without generating them all
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