Memoization ensures that a function doesn't run for the same inputs more than once by keeping a record of the results for given inputs (usually in a dictionary).
For example, a simple recursive function for computing the nth fibonacci number:
Will run on the same inputs multiple times:
We can imagine the recursive calls of this function as a tree, where the two children of a node are the two recursive calls it makes. We can see that the tree quickly branches out of control:
To avoid the duplicate work caused by the branching, we can wrap the function in a class that stores an instance variable, memo, that maps inputs to outputs. Then we simply:
- Check memo to see if we can avoid computing the answer for any given input, and
- Save the results of any calculations to memo.
We save a bunch of calls by checking the memo:
Now in our recurrence tree, no node appears more than twice:
Memoization is a common strategy for dynamic programming problems, which are problems where the solution is composed of solutions to the same problem with smaller inputs (as with the fibonacci problem, above). The other common strategy for dynamic programming problems is going bottom-up, which is usually cleaner and often more efficient.
Pass Your Interviews with My FREE 7-Day Crash Course
I'll teach you the right way of thinking for breaking down tricky algorithmic coding interview questions you've never seen before.
No prior computer science training necessary—I'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe if you hate it.