Count the Number of Inversions Problem
Description
LeetCode Problem 3193.
You are given an integer n and a 2D array requirements, where requirements[i] = [end_i, cnt_i] represents the end index and the inversion count of each requirement.
A pair of indices (i, j) from an integer array nums is called an inversion if:
i < jandnums[i] > nums[j]
Return the number of permutations perm of [0, 1, 2, ..., n - 1] such that for all requirements[i], perm[0..end_i] has exactly cnt_i inversions.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, requirements = [[2,2],[0,0]]
Output: 2
Explanation:
The two permutations are:
- [2, 0, 1]
- Prefix [2, 0, 1] has inversions (0, 1) and (0, 2).
- Prefix [2] has 0 inversions.
- [1, 2, 0]
- Prefix [1, 2, 0] has inversions (0, 2) and (1, 2).
- Prefix [1] has 0 inversions.
Example 2:
Input: n = 3, requirements = [[2,2],[1,1],[0,0]]
Output: 1
Explanation:
The only satisfying permutation is [2, 0, 1]:
- Prefix [2, 0, 1] has inversions (0, 1) and (0, 2).
- Prefix [2, 0] has an inversion (0, 1).
- Prefix [2] has 0 inversions.
Example 3:
Input: n = 2, requirements = [[0,0],[1,0]]
Output: 1
Explanation:
The only satisfying permutation is [0, 1]:
- Prefix [0] has 0 inversions.
- Prefix [0, 1] has no inversions.
Constraints:
2 <= n <= 3001 <= requirements.length <= nrequirements[i] = [end_i, cnt_i]0 <= end_i <= n - 10 <= cnt_i <= 400- The input is generated such that there is at least one
isuch thatend_i == n - 1. - The input is generated such that all
end_iare unique.
Solution
Approach: Dynamic Programming
Let f[i][j] be the number of ways to arrange the first i + 1 positions of a permutation so that they have j inversions. When the element at position i is placed, it can form between 0 and i new inversions with the earlier ones, so f[i][j] is the sum of f[i - 1][j - k] for k from 0 to min(i, j). If position i ends a requirement [end, cnt], only j = cnt is computed and all other states are 0. The answer is f[n - 1][cnt] for the requirement at n - 1. If a requirement for index 0 asks for a positive count, the answer is 0.
Complexity: O(n * m * min(n, m)) time and O(n * m) space, where m <= 400 is the largest inversion count.
class Solution:
def numberOfPermutations(self, n: int, requirements: List[List[int]]) -> int:
req = [-1] * n
for end, cnt in requirements:
req[end] = cnt
if req[0] > 0:
return 0
req[0] = 0
mod = 10**9 + 7
m = max(req)
f = [[0] * (m + 1) for _ in range(n)]
f[0][0] = 1
for i in range(1, n):
l, r = 0, m
if req[i] >= 0:
l = r = req[i]
for j in range(l, r + 1):
# f[i - 1][j - k] for k = 0 .. min(i, j)
f[i][j] = sum(f[i - 1][j - min(i, j) : j + 1]) % mod
return f[n - 1][req[n - 1]]