Data Structures & Algorithms / Module 9: Dynamic programming

Topic 9.1

Memoization

Writing answers down so the same sub-problem is never worked out twice.

9 min · intermediate

Watch: without notes, the same question is worked out again and again. With notes, each answer is worked out once and reused.

f5
  • moving now
  • finished / the result
Step 1 of 16

f(5) needs f(4) and f(3).

Without a memo, f3 is worked out twice and f2 three times. With a memo, every value is worked out once and the rest is read from the notes.

Work done twice

fib(5) needs fib(4) and fib(3). But fib(4) needs fib(3) too. So fib(3) is worked out twice, fib(2) three times, and so on. Press Step in the "no memo" figure and count how often f2 appears. Each time n goes up by one, the number of calls grows about 1.6 times. fib(40) needs over 300 million calls, though there are only 41 different values.

Write it down, check your notes first

Like a student jotting results in the margin: before working something out, check whether you already have. With a memo, every fib(k) is computed once. The remaining calls get their answer from the notes straight away, with no further calls. That's about 2n calls in total: O(n).

Code, for programmersFibonacci with a memo
function fib(n, memo = new Map()) {
  if (n < 2) return n;                    // base case
  if (memo.has(n)) return memo.get(n);    // already worked out: reuse it
  const value = fib(n - 1, memo) + fib(n - 2, memo);
  memo.set(n, value);                     // write it down before returning
  return value;
}

fib(40);   // 102334155, in about 80 calls instead of 331 million

When a memo helps

Two conditions:

  • Overlapping sub-problems: the same question comes up again and again. Merge sort doesn't have this (every piece is different), so a memo doesn't help.
  • A pure function: the same input always gives the same answer, with no side effects. Don't memoize functions that read the clock, a database, or random numbers.

Quiz

  1. Why is plain recursive fib so slow?

  2. Which function is not safe to memoize?

  3. With a memo, roughly how many calls does fib(n) make?

0 of 3 answered.