title: Number of n-element permutations with exactly k inversions
body: <p>I am trying to efficiently solve <a href="http://www.spoj.com/problems/PERMUT1/" rel="nofollow noreferrer">SPOJ Problem 64: Permutations</a>.</p>
  
  <blockquote>
    <p>Let A = [a1,a2,...,an] be a permutation of integers 1,2,...,n. A pair
    of indices (i,j), 1&lt;=i&lt;=j&lt;=n, is an inversion of the permutation A if
    ai>aj. We are given integers n>0 and k>=0. What is the number of
    n-element permutations containing exactly k inversions?</p>
    
    <p>For instance, the number of 4-element permutations with exactly 1
    inversion equals 3.</p>
  </blockquote>
  
  <p>To make the given example easier to see, here are the three 4-element permutations with exactly 1 inversion:</p>
  
  <pre><code>(1, 2, 4, 3)
  (1, 3, 2, 4)
  (2, 1, 3, 4)
  </code></pre>
  
  <p>In the first permutation, 4 > 3 and the index of 4 is less than the index of 3. This is a single inversion. Since the permutation has exactly one inversion, it is one of the permutations that we are trying to count.</p>
  
  <p>For any given sequence of n elements, the number of permutations is factorial(n). Thus if I use the brute force n<sup>2</sup> way of counting the number of inversions for each permutation and then checking to see if they are equal to k, the solution to this problem would have the time complexity O(n! * n<sup>2</sup>).
  <hr></p>
  
  <h1>Previous Research</h1>
  
  <p>A subproblem of this problem was previously asked <a href="https://stackoverflow.com/questions/6523712/calculating-the-number-of-inversions-in-a-permutation">here</a> on StackOverflow. An O(n log n) solution using merge sort was given which counts the number of inversions in a <em>single</em> permutation. However, if I use that solution to count the number of inversions for each permutation, I would still get a time complexity of O(n! * n log n) which is still very high in my opinion.</p>
  
  <p>This <a href="https://stackoverflow.com/questions/17504758/number-of-permutation-with-exact-k-inversions">exact question was also asked previously on Stack Overflow but it received no answers.</a></p>
  
  <p><hr>
  My goal is to avoid the factorial complexity that comes from iterating through all permutations. Ideally I would like a mathematical formula that yields the answer to this for any n and k but I am unsure if one even exists.</p>
  
  <p>If there is no math formula to solve this (which I kind of doubt) then I have also seen people giving hints that an efficient dynamic programming solution is possible. Using DP or another approach, I would really like to formulate a solution which is more efficient than O(n! * n log n), but I am unsure of where to start.</p>
  
  <p>Any hints, comments, or suggestions are welcome.</p>
  
  <p>EDIT: I have answered the problem below with a DP approach to computing <a href="http://oeis.org/A008302" rel="nofollow noreferrer">Mahonian numbers</a>.</p>