Skip to content
BytePatterns

Memoization

Recursion: lesson 4 of 8

Write each answer down once, never solve it twice.

Lesson 4 of 8 · 5 min

Memoization

Step 1 of 11

Same fib(5), one line added: before recursing, look in a memo dictionary.

The Idea

Memoization stores each subproblem's answer the first time you compute it. Every later call with the same input reads the stored value instead of recursing again. The shape of the code barely changes, but the cost collapses from exponential to linear.

Real-World Example

A translator working through a technical manual keeps a glossary card for every term they look up. The second time "torque converter" appears, they read their own card instead of opening the dictionary from scratch.

The Code

def fib(n, memo=None):
    if memo is None:
        memo = {}
    if n < 2:
        return n
    if n in memo:                              # solved before: reuse it
        return memo[n]
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
    return memo[n]

print(fib(35))   # 9227465, in 69 calls instead of nearly 30 million

Python

Your turn

What does this print?

calls = 0
memo = {}

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

f(5)
print(calls)

Mini quiz

1 / 3

Memoizing naive Fibonacci changes its running time from:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.