Skip to content
Problem 629 · LeetCode 629(opens in a new tab)

K Inverse Pairs Array

HardDynamic programming

Take an ordering of the numbers 1 to n. An inverse pair is two positions where the earlier number is larger than the later one. For example, [3, 1, 2] has two of them: 3 before 1 and 3 before 2.

Given n and k, count the orderings of 1 to n that have exactly k inverse pairs. The count can be very large, so return it modulo 1,000,000,007.

Example 1

Input:  n = 4, k = 2
Output: 5
Why:    1342, 1423, 2143, 2314 and 3124 each have two
2 more examples and the constraints

Example 2

Input:  n = 3, k = 3
Output: 1
Why:    only [3, 2, 1] is fully reversed

Example 3

Input:  n = 2, k = 5
Output: 0
Why:    two numbers make at most one pair

Constraints

  • 1 ≤ n ≤ 1,000
  • 0 ≤ k ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP, sum each windowO(n·k·min(n, k))
  2. DP with a sliding windowO(n·k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = k = 1,000Verdict
DP, sum each windowO(n·k·min(n, k))
Correct; slow inner sum
DP with a sliding windowO(n·k)
Best; O(1) per cell

n = how many numbers, k = the number of inverse pairs wanted.

Edge cases to test

  • k = 0. Only the sorted ordering has no pairs, so the answer is 1 for every n.
  • k larger than possible. n numbers have at most n(n − 1)/2 pairs; n = 2, k = 5 gives 0.
  • Fully reversed. k = n(n − 1)/2 also gives 1: n = 3, k = 3 is only [3, 2, 1].
  • n = 1. One number has no pairs: 1 when k = 0, otherwise 0.
  • Huge counts. n = k = 1,000 overflows any integer type without the modulo after every step.

Common mistakes

  • Letting the new number add up to j pairs instead of at most i − 1, which counts impossible placements.
  • Forgetting to subtract the cell that leaves the window, which turns the window into a full prefix sum.
  • Taking the modulo of a difference without adding MOD back, giving a negative count in Java, C++ or TypeScript.

How to talk through it

  1. 1Clarify. Is it orderings of exactly 1 to n? Is the answer modulo 1,000,000,007? How large can k be?
  2. 2Give the brute force. Generating all n! orderings is out, so define dp[i][j] and say each cell sums up to i earlier cells.
  3. 3Explain the insertion. Number i is the largest; placing it p spots from the end adds exactly p pairs.
  4. 4Code the sliding window. Keep a running total: add dp[j], subtract dp[j − i], take the modulo safely.
  5. 5Test out loud. Check n = 4, k = 2 by hand (5), k = 0 (1) and an impossible k (0) before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?