Count number of derangements (Memoization)

Given a number n, find number of derangements in a set of n elements. A Derangement is a permutation with no element appears in its original position. For example, a derangement of [0, 1, 2] is [2, 0, 1].

Hint

This algorithm uses memoization to improve performance. It's same as the recursive version of Count number of derangements, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:

# Python implementation
cache = {}

def placement(n):
  if n == 1:
    return 0

  if n == 2:
    return 1
  
  if n not in cache:
    cache[n] = (n - 1) * (placement(n - 1) + placement(n - 2))

  return cache[n]

n = 4

print(placement(n))
// Javascript implementation
let cache = [];

function placement(n) {
  if (n == 1) {
    return 0;
  }

  if (n == 2) {
    return 1;
  }

  if (cache[n] === undefined) {
    cache[n] = (n - 1) * (placement(n - 1) + placement(n - 2));
  }

  return cache[n];
}

const n = 4;

console.log(placement(n));