CodeBlanks Logo Icon CodeBlanks

What is memoization?

Cache sub-results to avoid recomputation.

What is memoization?

Memoization stores computed sub-results in a cache to prevent recomputation.

In recursive Fibonacci the same subproblem is solved many times; memoization prevents this.

Memoization turns exponential complexity into polynomial; fibonacci becomes Θ(n).

The cache

The cache is usually a dictionary or array. The key is the subproblem's parameter.

On first compute the result is written to the cache; later calls read from it.

So each subproblem is solved only once; total time drops.

Practice Fibonacci comparison

Write fib_naive(n). Recursive naive Fibonacci. Print 55 with print(fib_naive(10)).

Starter code

solution.py
def fib_naive(n):
    # Naive Fibonacci

Sample solution

solution.py
def fib_naive(n):
    # Naive Fibonacci
    if n <= 1:
        return n
    return fib_naive(n - 1) + fib_naive(n - 2)
print(fib_naive(10))

Expected output

55

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does memoization prevent?

  • Recomputation Correct answer
  • Memory usage
  • Recursion
  • Loops

Explanation: Recomputation.

2 Cache structure

Question
memo = ____
Answer
memo = {}

Explanation: {} is right.

3 What is memoization: match the terms

Term Meaning
memoization Cache
cache Dictionary
subproblem Subproblem
recursion Self-call

All lessons in Advanced