KatInterview

Rearrangements of 1..m With a Fixed Number of Out-of-Order Pairs

Dynamic ProgrammingAuto-graded · 28 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingcombinatoricspermutations

Last updated

Count arrangements of 1..m with exactly n out-of-order pairs, modulo 10^9+7, using a DP over insertion positions optimized with a sliding-window sum.

You are given two integers m and n.

Think about every ordering of the numbers 1, 2, ..., m, where each number appears exactly once. In an ordering p (0-indexed), a pair of positions (i, j) is out of order if i < j and p[i] > p[j].

Count how many orderings of 1..m contain exactly n out-of-order pairs. Because the count can be huge, return it modulo 10^9 + 7.

Details

  • An ordering with no out-of-order pairs is the sorted one, [1, 2, ..., m].
  • If n is larger than the number of pairs that can possibly be out of order, the answer is 0.
  • Only the count modulo 10^9 + 7 is returned, as a non-negative integer in [0, 10^9 + 6].

Implement count_orderings(m, n) returning that count.

Constraints

  • 1 <= m <= 1000
  • 0 <= n <= 1000

Examples

Example 1

Input: count_orderings(3, 0)

Output: 1

Example 2

Input: count_orderings(3, 1)

Output: 2

Example 3

Input: count_orderings(4, 3)

Output: 6

Example 4

Input: count_orderings(1, 0)

Output: 1

Hints

Hint 1

Think about building the ordering by inserting the values 1, 2, ..., m one at a time. What happens to the out-of-order pair count when you insert the current largest value?

Hint 2

If the new largest value is placed so that k elements come after it, it adds exactly k out-of-order pairs, for any k from 0 to (current size - 1). This gives dp[i][j] as a sum of up to i entries from the previous row.

Hint 3

That sum is a window of width i over the previous row. Maintain it as a running sum: add prev[j], and once j >= i subtract prev[j - i]. Keep everything modulo 10^9+7 and only store two rows.