Find the Number of permutation with K inversions using C++

C++Server Side ProgrammingProgramming

In an array, A pair a[i], a[j] is known as an inversion if a[i] > a[j] and i < j. We have two numbers N and k, and need to figure out how many possible permutations of the first N numbers end in a perfect K inversion. So here is the example −

Input: N = 4, K = 1
Output: 3
Explanation: Permutation of the first N numbers in total : 1234, 1243, 1324 and 2134. With 1 inversion we have 1243, 1324 and 2134.

Input : N = 3, K = 2
Output : 3
Explanation: Permutation of the first N numbers in total : 123, 132, 213, 231, 312, and 321 with 2 inversions we have 231, 312 and 321.

Approach to Find Solution

We can apply the Brute force approach, which is first finding all the permutations of first N numbers and then checking all the inversions whether it is equal to K or not. If yes, then incrementing the resulting counter.

Efficient Approach

In this approach, we have N digits of first N natural numbers. All permutations of that number are calculated somewhere else from which we are looking for K permutations. To find it, We will be inserting the next number Nth(largest) in all permutations and looking for those numbers whose inversion count is equal to K after adding this number should be counted in our result. Taking such permutations of (N – 1) numbers that do not have (K – 3) inversion, we will shift the new number at the 3rd index from last. The number of inversions will be K, and find_permutations(N-1, K-3) will be our answer. The same logic can be used for other inversions, and we'll arrive at the above recursion as the final answer.


#include <bits/stdc++.h>
using namespace std;
const int X = 100;
int a = 0;
int arr[X][X];
// recursive function
int find_permutations (int N_numbers, int K_inversion){
    if (N_numbers == 0){
      return 0;            // return 0 when N becomes 0
    if (K_inversion == 0)
        return 1;            // return 1 when K becomes 1
    if (arr[N_numbers][K_inversion] != 0)
        return arr[N_numbers][K_inversion];
    int result = 0;
    for (int i = 0; i <= K_inversion; i++){

        if (i <= N_numbers - 1)
          result += find_permutations (N_numbers - 1, K_inversion - i);
    arr[N_numbers][K_inversion] = result;
    return result;
// main function
int main (){
    int N, K;
    cin >> N;    // taking input from user
    cin >> K;
    cout << find_permutations (N, K);
    return 0;



Input − N = 4, K = 3

Output − 6


In this article, we solve a problem to find the Number of permutations with K inversions from O(n * k) time complexity. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.

Updated on 24-Nov-2021 07:36:22