Bitpath

Lesson 2 · Unit 02

Remember answers

Memoization turns a tree back into a chain

11 exercisesabout 3 min

What you practise

  • A memo map
  • Calls drop to O(n)
  • Order of check, compute, store

Try a question from this lesson

Pick one

Plain fib(30) makes 2,692,537 calls. This version writes every answer down the first time. What does it print?

calls = 0
memo = {}

def fib(n):
    global calls
    calls += 1
    if n < 2:
        return n
    if n not in memo:
        memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]

fib(30)
print(calls)
let calls = 0;
const memo = new Map();

function fib(n) {
  calls += 1;
  if (n < 2) return n;
  if (!memo.has(n)) {
    memo.set(n, fib(n - 1) + fib(n - 2));
  }
  return memo.get(n);
}

fib(30);
console.log(calls);
let calls = 0;
const memo = new Map<number, number>();

function fib(n: number): number {
  calls += 1;
  if (n < 2) return n;
  if (!memo.has(n)) {
    memo.set(n, fib(n - 1) + fib(n - 2));
  }
  return memo.get(n)!;
}

fib(30);
console.log(calls);

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Memoization

Branching recursion repeats itself: the same input, the same answer, computed again.

Memoization keeps a map from input to answer. On each call: look in the memo first. On a miss, compute the answer, store it, then return it. On a hit, return what is stored and skip the whole subtree.

9 more exercises in the app

  • 1× fill the blanks
  • 2× type the answer
  • 3× multiple choice
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy