Find the Index of Permutation - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code