Count the Number of Inversions - Problem
Count the Number of Inversions
You're given an integer
What is an inversion?
In an array, an inversion is a pair of indices
Your Goal:
Find how many permutations of
Since the answer can be very large, return it modulo
Example: If
You're given an integer
n and a 2D array requirements, where each requirements[i] = [end_i, cnt_i] represents a constraint on the permutation.What is an inversion?
In an array, an inversion is a pair of indices
(i, j) where i < j but nums[i] > nums[j]. It's essentially when a larger element appears before a smaller one.Your Goal:
Find how many permutations of
[0, 1, 2, ..., n-1] satisfy ALL the given requirements. For each requirement [end_i, cnt_i], the subarray perm[0..end_i] must have exactly cnt_i inversions.Since the answer can be very large, return it modulo
109 + 7.Example: If
n=3 and requirements=[[2,2]], we need permutations where the first 3 elements have exactly 2 inversions. The permutation [2,1,0] works because it has inversions: (0,1), (0,2), (1,2) - but wait, that's 3 inversions, not 2! Input & Output
example_1.py — Basic Case
$
Input:
n = 3, requirements = [[2,2]]
›
Output:
2
💡 Note:
We need permutations of [0,1,2] where the first 3 elements have exactly 2 inversions. Valid permutations: [2,0,1] has inversions (0,1), (0,2) = 2 total. [1,2,0] has inversions (0,2), (1,2) = 2 total.
example_2.py — Multiple Requirements
$
Input:
n = 3, requirements = [[0,0], [2,2]]
›
Output:
1
💡 Note:
First element (arr[0]) must create 0 inversions with itself (which is always true), and the entire array must have exactly 2 inversions. The permutation [0,2,1] satisfies both: arr[0..0] has 0 inversions, and arr[0..2] has 1 inversion at (1,2).
example_3.py — Impossible Case
$
Input:
n = 2, requirements = [[0,1]]
›
Output:
0
💡 Note:
With only 1 element at position 0, it's impossible to have 1 inversion since inversions need at least 2 elements.
Constraints
- 2 ≤ n ≤ 300
- 0 ≤ requirements.length ≤ n
- requirements[i] = [endi, cnti]
- 0 ≤ endi ≤ n - 1
- 0 ≤ cnti ≤ 400
- All endi are distinct
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code