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
Finding Position of 'BAC' in DictionaryStep 1: Count words starting with letters before 'B'ABCACBโ† 2 words start with 'A'Step 2: Among 'B*' words, count those with 2nd letter before 'A'BACโ† No letters come before 'A', so count = 0Step 3: Calculate final positionPosition = 2 + 0 = 2BAC is at index 2All arrangements in order:0: ABC1: ACB2: BAC โ† Found!3: BCA4: CAB5: CBA
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
42.1K Views
Medium Frequency
~25 min Avg. Time
1.8K 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