Count Permutations With Exact Inversion Pairs
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Tests deep combinatorics knowledge by counting permutations of 1..n that have exactly k inversions, using the Mahonian distribution and efficient DP with modular arithmetic.
Count Permutations With Exact Inversion Pairs
An inversion in a permutation is a pair of indices (i, j) with i < j but p[i] > p[j].
Given two integers n and k, count the number of permutations of [1, 2, ..., n] that have exactly k inversions. Return the answer modulo 10^9 + 7.
Background
When inserting the element with value m into a growing permutation of m-1 elements, placing it at position 0 (leftmost) creates m-1 new inversions, placing it at position 1 creates m-2, …, and placing it at the rightmost position creates 0. This observation drives a clean recurrence based on the Mahonian distribution (also known as the q-factorial coefficient).
Task
Implement count_permutations_k_inversions(n: int, k: int) -> int that returns the number of permutations of [1..n] with exactly k inversions, modulo 10^9 + 7.
Constraints
1 <= n <= 5000 <= k <= 500- If
kis larger than the maximum possible number of inversions forn(which isn*(n-1)//2), return0. - The answer must be reduced modulo
10^9 + 7.
Examples
Example 1
Input: count_permutations_k_inversions(3, 2)
Output: 2
Example 2
Input: count_permutations_k_inversions(4, 0)
Output: 1
Example 3
Input: count_permutations_k_inversions(4, 6)
Output: 1
Hints
Hint 1
Think about how inserting element m into a permutation of (m-1) elements contributes between 0 and m-1 new inversions — this gives a recurrence: dp[m][j] = sum of dp[m-1][j-t] for t in 0..m-1.
Hint 2
The inner sum is a sliding window sum (prefix sum trick), so each row of the DP table can be computed in O(k) rather than O(m*k), bringing the total to O(n*k).
Hint 3
You only need the previous row at each step, so space can be reduced to O(k). Also remember to clamp k at n*(n-1)//2 early to avoid unnecessary work.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: Building Permutations One Element at a Time
Consider building a permutation of [1..n] by inserting elements from largest to smallest (or equivalently, tracking the contribution of each new element). When inserting element m into an already-built permutation of m-1 elements, placing it at one of the m available positions contributes exactly t new inversions for t ∈ {0, 1, ..., m-1} (the number of previously-inserted elements that come after it). This is because all previously placed elements are smaller, so every element to the right of the new insertion point forms an inversion with it.
This gives the Mahonian recurrence:
dp[m][j] = sum_{t=0}^{min(j, m-1)} dp[m-1][j - t]
where dp[m][j] is the count of permutations of length m with exactly j inversions.
Efficient Computation with Prefix Sums
A naive evaluation of the recurrence is O(n·k·n) = O(n²·k). By computing a prefix sum array over the previous row, each new row entry reduces to a constant-time range query:
new_dp[j] = prefix[j+1] - prefix[max(0, j-(m-1))]
This brings the total complexity to O(n·k) time and O(k) space.
Correctness
- Base case: one permutation of length 1 with 0 inversions.
- Inductive step: each insertion is independent and exhaustive over all positions.
- Early exit: if
k > n*(n-1)/2, no permutation of lengthncan have that many inversions (the maximum is achieved by the reverse permutation). - Modular arithmetic: all additions and subtractions are taken mod
10^9+7; subtraction is kept non-negative by Python's native modulo behaviour.
Complexity
| Value | |
|---|---|
| Time | O(n · k) |
| Space | O(k) |
For n = 500, k = 500 this is 250 000 operations — well within limits.
from typing import List
def count_permutations_k_inversions(n: int, k: int) -> int:
MOD = 10**9 + 7
max_inv = n * (n - 1) // 2
if k > max_inv:
return 0
dp = [0] * (k + 1)
dp[0] = 1
for m in range(2, n + 1):
prefix = [0] * (k + 2)
for j in range(k + 1):
prefix[j + 1] = (prefix[j] + dp[j]) % MOD
new_dp = [0] * (k + 1)
for j in range(k + 1):
lo = max(0, j - (m - 1))
new_dp[j] = (prefix[j + 1] - prefix[lo]) % MOD
dp = new_dp
return dp[k]