K Inverse Pairs Array - Problem

An inverse pair in an integer array nums is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].

Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs.

Since the answer can be huge, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 0
Output: 1
💡 Note: Only one array [1,2,3] has 0 inverse pairs (already sorted)
Example 2 — One Inversion
$ Input: n = 3, k = 1
Output: 2
💡 Note: Two arrays have exactly 1 inverse pair: [1,3,2] and [2,1,3]
Example 3 — Edge Case
$ Input: n = 4, k = 6
Output: 1
💡 Note: Only [4,3,2,1] has maximum 6 inverse pairs for n=4

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ k ≤ 1000

Visualization

Tap to expand
K Inverse Pairs: n=3, k=1[1,2,3]Numbers 1→3k = 1Target inversionsFind all arrays with exactly 1 inversion[1,3,2]3 > 2 at (1,2)✓ 1 inversion[2,1,3]2 > 1 at (0,1)✓ 1 inversionAnswer: 2Valid arrangements
Understanding the Visualization
1
Input
n=3 numbers [1,2,3], need k=1 inversions
2
Process
Find all arrangements with exactly 1 inversion
3
Output
Count = 2 valid arrangements
Key Takeaway
🎯 Key Insight: When placing the largest number at position p, it creates exactly (n-1-p) new inverse pairs with smaller numbers to its right
Asked in
Google 25 Microsoft 18 Amazon 15
28.0K Views
Medium Frequency
~35 min Avg. Time
890 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