TExcelTAD

Memoization

Memoization means remembering the results of function calls so that a repeated call with the same arguments returns the stored answer instead of recomputing it. It turns many slow recursive algorithms into fast ones with a few extra lines, and it is the top-down way of doing dynamic programming.

The word comes from "memo": a note to yourself.

The problem: overlapping subproblems

The recursive Fibonacci function from the Simple Algorithm lesson is short and correct, but painfully slow:

python · try it yourself
calls = {}

def fib(n):
    calls[n] = calls.get(n, 0) + 1
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print("fib(15) =", fib(15))
print("total calls:", sum(calls.values()))
print("how often each n was computed:", {n: calls[n] for n in sorted(calls)})
fib(15) = 610
total calls: 1973
how often each n was computed: {0: 377, 1: 610, 2: 377, 3: 233, 4: 144, 5: 89, 6: 55, 7: 34, 8: 21, 9: 13, 10: 8, 11: 5, 12: 3, 13: 2, 14: 1, 15: 1}

fib(15) calls itself almost 2000 times, although there are only 16 different values of n. fib(1) alone is computed 610 times. The subproblems overlap: the same small Fibonacci numbers are needed over and over by different branches of the call tree.

The fix: a memo dictionary

Before computing, check the memo; after computing, store the result.

python · try it yourself
memo = {}
calls = 0

def fib(n):
    global calls
    calls += 1
    if n in memo:
        return memo[n]          # already known: no recursion
    result = n if n <= 1 else fib(n - 1) + fib(n - 2)
    memo[n] = result
    return result

print("fib(15) =", fib(15), "with", calls, "calls")
calls = 0
print("fib(90) =", fib(90), "with", calls, "more calls")
fib(15) = 610 with 29 calls
fib(90) = 2880067194370816120 with 151 more calls

Each fib(k) is now computed once, so the work is O(n) instead of roughly O(1.6ⁿ). Computing fib(90) the naive way would take billions of years; with the memo it is instant.

Python's built-in memo: functools.cache

The standard library has a decorator that does exactly this. @cache (or @lru_cache(maxsize=None)) stores results keyed by the arguments:

python · try it yourself
from functools import cache

@cache
def fib(n):
    return n if n <= 1 else fib(n - 1) + fib(n - 2)

print(fib(100))
print(fib.cache_info())
354224848179261915075
CacheInfo(hits=98, misses=101, maxsize=None, currsize=101)

Note: The arguments must be hashable (numbers, strings, tuples), because they become dictionary keys. Lists won't work: convert them to tuples first.

A grid example: counting paths

How many ways can a robot go from the top-left to the bottom-right corner of a grid if it can only move right or down? From any cell, the number of paths is the sum of the paths from the cell to its right and from the cell below:

python · try it yourself
from functools import cache

@cache
def paths(rows, cols):
    if rows == 1 or cols == 1:
        return 1                 # a single row or column: only one way
    return paths(rows - 1, cols) + paths(rows, cols - 1)

print(paths(3, 3))
print(paths(10, 10))
print(paths(18, 18))
print(paths.cache_info().currsize, "different subproblems were solved")
6
48620
2333606220
323 different subproblems were solved

Without the cache, paths(18, 18) would make over a billion calls; with it, each (rows, cols) pair is solved once.

Memoizing with blocked cells

Memoization shines when the recursion has extra conditions. Here some cells are blocked (#):

python · try it yourself
from functools import cache

grid = [
    "....",
    ".#..",
    "...#",
    "#...",
]

@cache
def count(r, c):
    if r >= len(grid) or c >= len(grid[0]) or grid[r][c] == "#":
        return 0
    if (r, c) == (len(grid) - 1, len(grid[0]) - 1):
        return 1
    return count(r + 1, c) + count(r, c + 1)

print("paths avoiding the blocks:", count(0, 0))
paths avoiding the blocks: 3

When does memoization help?

Memoization helps when a problem has:

  1. Optimal substructure: the answer can be built from answers to smaller instances of the same problem.
  2. Overlapping subproblems: those smaller instances repeat.

If the subproblems don't repeat (merge sort, for example, never sorts the same half twice), memoization only adds overhead.

Naive recursion Memoized recursion
Fibonacci fib(n) O(1.6ⁿ) calls O(n)
Grid paths rows × cols exponential O(rows · cols)
Extra memory call stack call stack + memo table

Tip: Deep recursion can hit Python's recursion limit (about 1000). For very large inputs, convert the memoized solution to tabulation (next lesson), which fills the table with loops instead.

Test yourself

What does memoization store?

  1. The source code of a function
  2. Results of previous calls, keyed by their arguments
  3. The call stack
  4. Only the last result

Why is naive recursive Fibonacci slow?

  1. Addition is slow
  2. It solves the same subproblems many times
  3. Recursion is always slow
  4. It uses floating point

Which of these arguments can NOT be used with functools.cache directly?

  1. An int
  2. A string
  3. A tuple
  4. A list