Find the Index of Permutation - Problem
Imagine you have all possible arrangements (permutations) of numbers [1, 2, ..., n] listed in dictionary order (lexicographic order). Your task is to find the position of a specific permutation in this sorted list.
Given an array perm of length n which is a permutation of [1, 2, ..., n], return the 0-based index of perm in the lexicographically sorted array of all permutations of [1, 2, ..., n].
For example, if n = 3, all permutations in order are: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]. If perm = [2,1,3], it's at index 2.
Since the answer may be very large, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic Case
$
Input:
perm = [1,2,3]
โบ
Output:
0
๐ก Note:
This is the first permutation in lexicographic order, so its index is 0.
example_2.py โ Middle Case
$
Input:
perm = [2,1,3]
โบ
Output:
2
๐ก Note:
All permutations in order: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]. The permutation [2,1,3] is at index 2.
example_3.py โ Last Case
$
Input:
perm = [3,2,1]
โบ
Output:
5
๐ก Note:
This is the last permutation in lexicographic order (reverse sorted), so its index is 3! - 1 = 5.
Constraints
- 1 โค n โค 1000
- perm is a valid permutation of [1, 2, ..., n]
- Return result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Count by First Letter
How many words start with letters before 'B'? All words starting with 'A' come first.
2
Count by Second Letter
Among words starting with 'B', how many have second letters before 'A'? None, since A is smallest.
3
Final Position
Add up all the counts to get the exact position without generating every arrangement.
Key Takeaway
๐ฏ Key Insight: Instead of generating all permutations, use factorial arithmetic to count how many permutations come before the target, giving us direct access to its position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code