Algorithms Made Simple

Memoization: Stop Solving the Same Subproblem Twice

How remembering answers turns a 300-million-call recursion into about 40 computations.

Algorithms Made Simple · 4 min read

Some recursive solutions repeat the same work again and again. Remembering the answers turns an impossible calculation into an instant one.

A wasteful recursion

The Fibonacci numbers are defined by fib(n) = fib(n − 1) + fib(n − 2). A direct recursive program recomputes the same values over and over. Calculating fib(40) this way makes over 300 million calls, even though only 40 distinct values are involved.

Remember what you computed

Memoization stores each result in a table the first time it is computed. Before computing a value, check the table. With this change, fib(40) needs only about 40 real computations, plus quick lookups.

When it works

Memoization helps when two conditions hold. First, the problem breaks into smaller subproblems of the same kind. Second, those subproblems overlap, so the same ones appear many times. If subproblems never repeat, as in merge sort, a table gives no benefit.

Top-down and bottom-up

The recursive version with a table is the top-down style. Filling the table from the smallest cases upward is the bottom-up style, usually called dynamic programming. Both give the same answers, and the bottom-up version avoids deep recursion.

The trade

You spend memory to save time. Check that the table fits, and decide what exactly identifies a subproblem, since that choice defines your table.

More guides from this book