Magicsheet logo

K Inverse Pairs Array

Hard
100%
Updated 6/1/2025

K Inverse Pairs Array

1. What is this problem about?

The K Inverse Pairs Array interview question is a difficult combinatorial problem. An inverse pair in a permutation p is a pair (i,j)(i, j) such that i<ji < j and p[i]>p[j]p[i] > p[j]. You are given two integers nn and kk, and you need to find the total number of permutations of 1…n1 \dots n that have exactly kk inverse pairs.

2. Why is this asked in interviews?

Tech giants like Microsoft and Google ask the K Inverse Pairs coding problem to test a candidate's mastery of Dynamic Programming and optimization. It requires deriving a complex recurrence relation and then optimizing it using Prefix Sums to avoid O(N⋅K2)O(N \cdot K^2) complexity. It’s a top-tier Math interview pattern.

3. Algorithmic pattern used

This problem is solved using DP with Prefix Sum Optimization.

  1. DP State: dp[i][j] is the number of permutations of length i with j inverse pairs.
  2. Transition: When adding the ithi^{th} number to a permutation of size i−1i-1, you can create between 0 and i−1i-1 new inverse pairs.
    • dp[i][j] = sum(dp[i-1][j-m]) for 0≤m<i0 \leq m < i.
  3. Optimization: The sum is over a range of the previous row. Use a prefix sum of the previous row to calculate this in O(1)O(1).
  4. Complexity: O(N⋅K)O(N \cdot K) time and O(K)O(K) space.

4. Example explanation

n=3,k=1n = 3, k = 1.

  • dp[2][0] = 1 ([1, 2]), dp[2][1] = 1 ([2, 1]).
  • To get 1 pair in n=3n=3:
    • Add '3' at the end (0 new pairs): need 1 pair from n=2n=2. dp[2][1] = 1.
    • Add '3' in the middle (1 new pair): need 0 pairs from n=2n=2. dp[2][0] = 1. Total: 2. ([1, 3, 2] and [2, 1, 3]).

5. Common mistakes candidates make

  • O(N⋅K2)O(N \cdot K^2) approach: Failing to use prefix sums for the range addition, leading to a Time Limit Exceeded.
  • Modulo errors: Forgetting to handle negative results when using prefix sum subtraction: (S[j] - S[j-i] + MOD) % MOD.
  • Space Complexity: Using a full 2D table when only the previous row is needed.

6. Interview preparation tip

Combinatorial DP problems often involve "transitions based on position." For permutations, adding an element at position XX always adds N−1−XN - 1 - X inversions. This visualization is the key to many "Hard" Dynamic Programming interview patterns.

Similar Questions