K Inverse Pairs Array - Problem
Imagine you're arranging numbers from 1 to n in a specific way to create exactly k inverse pairs. An inverse pair occurs when a larger number appears before a smaller number in the array - like having 3 before 1 in [3, 2, 1]. Your Challenge: Given two integers n and k, determine how many different arrays can be formed using numbers 1 to n such that there are exactly k inverse pairs. For example, with n=3 and k=1, the arrays [1,3,2], [2,1,3], and [3,1,2] each have exactly one inverse pair. Since the result can be enormous, return it modulo 109 + 7.

Input & Output

example_1.py โ€” Basic case with small numbers
$ Input: n = 3, k = 0
โ€บ Output: 1
๐Ÿ’ก Note: Only the array [1,2,3] has exactly 0 inverse pairs (it's already sorted)
example_2.py โ€” Multiple valid arrangements
$ Input: n = 3, k = 1
โ€บ Output: 2
๐Ÿ’ก Note: Arrays [1,3,2], [2,1,3] each have exactly 1 inverse pair: (3,2) and (2,1) respectively
example_3.py โ€” Maximum inversions case
$ Input: n = 4, k = 6
โ€บ Output: 1
๐Ÿ’ก Note: Only [4,3,2,1] has the maximum 6 inverse pairs: (4,3), (4,2), (4,1), (3,2), (3,1), (2,1)

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • 0 โ‰ค k โ‰ค 1000
  • Maximum possible inverse pairs for n numbers is nร—(n-1)/2
  • Result must be returned modulo 109 + 7

Visualization

Tap to expand
K Inverse Pairs: Visual UnderstandingExample: n=3, k=1 (Find arrays with exactly 1 inverse pair)Valid Arrays:[1, 3, 2] โ†’ (3,2) = 1 pair โœ“[2, 1, 3] โ†’ (2,1) = 1 pair โœ“Invalid Arrays:[1, 2, 3] โ†’ 0 pairs โœ—[3, 2, 1] โ†’ 3 pairs โœ—DP Insight: Placing Number 3Position 0 (first): [3,_,_] โ†’ 0 new inversionsNeed dp[2][1] ways for remainingPosition 1 (middle): [_,3,_] โ†’ 1 new inversionNeed dp[2][0] ways for remainingPosition 2 (last): [_,_,3] โ†’ 2 new inversionsNeed dp[2][-1] = 0 (impossible)DP Formula:dp[n][k] = ฮฃ dp[n-1][k-i] for i = 0 to min(k, n-1)๐ŸŽฏ Key: Each number placement creates predictable inversions with previous numbers
Understanding the Visualization
1
Understand Inverse Pairs
An inverse pair (i,j) means arr[i] > arr[j] but i < j - larger number appears before smaller
2
Recursive Structure
When placing largest number n at position i, it creates i inverse pairs with all previous smaller numbers
3
DP Transition
dp[n][k] = sum of dp[n-1][k-i] for i from 0 to min(k, n-1)
4
Optimization
Use prefix sum to compute each dp[i][j] in O(1) instead of O(k) time
Key Takeaway
๐ŸŽฏ Key Insight: When placing the largest number n, its position determines exactly how many new inverse pairs are created, allowing us to break down the problem recursively and solve it efficiently with dynamic programming.
Asked in
Google 24 Amazon 18 Microsoft 12 Meta 8
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen