Find number of permutation with K inversions (Tabulation)

Given two numbers n and k, find how many permutations of the first n number have exactly k inversion. An inversion is defined as a[i] > a[j] for i < j.

Hint

Building upon understanding of Find number of permutation with K inversions (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def count(n, k):
  cache = [[0] * (k + 1) for _ in range(n + 1)]
  cache[1][0] = 1

  for i in range(2, n + 1):
    for j in range(k + 1):
      for l in range(i):
        if j >= (i - l - 1):
          cache[i][j] += cache[i-1][j - (i - l - 1)]

  return cache[n][k]

n = 4
k = 2

print(count(n, k))
// Javascript implementation
function count(n, k) {
  const cache = Array.from(Array(n + 1), () => Array(k + 1).fill(0));
  cache[1][0] = 1;

  for (let i = 2; i < n + 1; i++) {
    for (let j = 0; j < k + 1; j++) {
      for (let l = 0; l < i; l++) {
        if (j >= (i - l - 1)) {
          cache[i][j] += cache[i - 1][j - (i - l - 1)]
        }
      }
    }
  }

  return cache[n][k];
}

const n = 4;
const k = 2;

console.log(count(n, k));