Find number of ways paint a fence with n posts and k colors (Memoization)

Find out the number of ways of painting a fence with n posts and k colors so that not more than two consecutive posts have the same color.

Hint

This algorithm uses memoization to improve performance. It's same as the recursive version of Find number of ways paint a fence with n posts and k colors, 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 = None

def count(n, k):
  if n == 1:
    return k

  if n == 2:
    return k * k
  
  global cache
  if not cache:
    cache = [None] * (n + 1)

  if not cache[n]:
    cache[n] = (k - 1) * (count(n - 1, k) + count(n - 2, k))

  return cache[n]

n = 3
k = 2

print(count(n, k))
// Javascript implementation
let cache = null;

function count(n, k) {
  if (n == 1) {
    return k;
  }

  if (n === 2) {
    return k * k;
  }

  if (!cache) {
    cache = Array(n + 1);
  }

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

  return cache[n];
}

const n = 3;
const k = 2;

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