Skip to content
BytePatterns

Memoization

Recursion: lesson 4 of 5

Write each answer down once, never solve it twice.

Lesson 4 of 5 · 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 35 steps instead of millions

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: