K Inverse Pairs Array - Problem

For an integer array nums, an inverse pair 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: Arrays [1,3,2] and [2,1,3] each have exactly 1 inverse pair
Example 3 — Edge Case
$ Input: n = 4, k = 2
Output: 5
💡 Note: Multiple arrays possible with exactly 2 inverse pairs

Constraints

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

Visualization

Tap to expand
INPUTn = 3, k = 13Array size1Target inversionsFind arrangements of [1,2,3]with exactly 1 inverse pairExample valid arrays:[1,3,2][2,1,3]ALGORITHM1Initialize DP table2Fill using recurrence3dp[i][j] = Σ dp[i-1][j-pos]4Return dp[n][k]DP Table (3x2):dp[2][0]=1, dp[2][1]=1dp[3][1] = 2RESULTCount of valid arrays2Arrays with exactly1 inverse pair:[1,3,2]: 3>2[2,1,3]: 2>1Output: 2Key Insight:Each number can create 0 to min(position, remaining inversions) new inverse pairs.Dynamic programming builds the solution incrementally with optimal substructure.TutorialsPoint - K Inverse Pairs Array | Optimized DP
Asked in
Google 15 Microsoft 12 Amazon 8
85.0K Views
Medium Frequency
~35 min Avg. Time
1.9K 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