KatInterview

Count Permutations With Exact Inversion Pairs

Math & Bit ManipulationAuto-graded · 19 test cases
HardAuto-gradedMath & Bit Manipulationcombinatoricsdynamic programmingnumber theory

Last 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 <= 500
  • 0 <= k <= 500
  • If k is larger than the maximum possible number of inversions for n (which is n*(n-1)//2), return 0.
  • 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.