Memoization is an optimization technique that stores the result of a function call in a lookup table keyed by its arguments, so that a later call with the same arguments returns the stored value instead of repeating the computation. In the study of algorithms within programming, it is the standard way to turn an exponential recursive solution into a polynomial one whenever the recursion keeps solving the same overlapping subproblems.
The idea trades memory for time: each distinct input is computed once, and every repeat costs only a lookup. The term was coined by Donald Michie in 1968 from the Latin word memorandum, and it is deliberately spelled without an r to distinguish it from ordinary memorization.
How memoization intercepts repeated calls
A memoized function checks a cache before doing any work. When the arguments form a key that is already present, the stored result is returned immediately; when the key is missing, the function computes the result, writes it to the cache and then returns it. The caller cannot tell the difference except through speed.
The classic illustration is the naive recursive Fibonacci function. Computing fib(40) without a cache triggers more than 300 million recursive calls, because fib(38), fib(37) and smaller values are recomputed again and again. With memoization, each of the 41 distinct inputs is evaluated exactly once, and the running time drops from roughly O(φ^n) to O(n).
The table below traces the components every memoized function needs, regardless of the language or library used to implement it.
| Component | Role | Typical implementation |
|---|---|---|
| Cache key | Identifies a distinct input | Tuple of arguments, string, or hash |
| Cache store | Holds computed results | Hash map, array, or dictionary |
| Lookup step | Returns a hit without recomputation | Constant-time map access |
| Compute step | Runs the original logic on a miss | The unmodified function body |
| Eviction policy | Limits memory growth | LRU, size cap, or none |
Conditions that make memoization correct
Memoization is safe only when the function is referentially transparent: the same arguments must always produce the same result, and the function must have no observable side effects. A function that reads the clock, a database, a random generator or mutable global state will return stale or wrong values once it is cached.
The second requirement is a well-defined key. Arguments must be hashable or reducible to a stable identifier. Mutable objects such as lists or dictionaries are dangerous keys, because a caller may modify the object after the call, and the cache then maps an outdated value to a key that no longer describes the input. Floating-point arguments raise a related problem, since values that are mathematically equal may differ in their last bits and miss the cache.
- Pure functions: deterministic output and no side effects.
- Immutable or hashable arguments: stable keys for every call.
- Overlapping inputs: the same arguments actually recur during execution.
- Bounded input space: the number of distinct keys fits in available memory.
Memoization compared with related techniques
Memoization is closely tied to dynamic programming, and the two are often described as top-down and bottom-up versions of the same strategy. Memoization keeps the natural recursive structure and fills the table lazily, only for subproblems that are actually reached. Bottom-up tabulation fills the table iteratively in a fixed order, which avoids recursion overhead but may compute entries that are never needed.
The comparison below separates memoization from the neighboring approaches with which it is most often confused.
| Approach | Order of evaluation | Main strength | Main weakness |
|---|---|---|---|
| Memoization | Top-down, on demand | Computes only reachable subproblems | Recursion depth and call overhead |
| Bottom-up tabulation | Iterative, fixed order | No stack limits, easy space reduction | May fill unused table entries |
| General caching | Any order, often external | Works across processes and requests | Needs invalidation for changing data |
| Divide and conquer | Top-down, no reuse | Simple for independent subproblems | Wastes work when subproblems overlap |
The distinction from general caching matters in practice. A web cache stores responses whose underlying data can change, so it relies on expiry times and invalidation. A memoization table assumes the result never becomes invalid, which is exactly why purity is a precondition.
Typical applications and their complexity gains
Memoization delivers its largest gains on recursive problems with overlapping subproblems, where the number of distinct states is far smaller than the number of recursive calls. The table lists common cases and the effect of caching on their running time.
| Problem | Distinct states | Without memoization | With memoization |
|---|---|---|---|
| Fibonacci numbers | n | Exponential | O(n) |
| Longest common subsequence | m × n | Exponential | O(m × n) |
| 0/1 knapsack | n × capacity | O(2^n) | O(n × capacity) |
| Edit distance | m × n | Exponential | O(m × n) |
| Counting grid paths | rows × columns | Exponential | O(rows × columns) |
Beyond textbook algorithms, memoization appears in parsers (packrat parsing guarantees linear time for parsing expression grammars), in compilers that cache type inference results, and in user interface frameworks that skip re-rendering a component when its inputs are unchanged. Many languages provide ready-made tools, such as functools.lru_cache and functools.cache in Python or memo helpers in JavaScript frameworks.
Costs, pitfalls and common mistakes
The main cost of memoization is memory proportional to the number of distinct keys. An unbounded cache in a long-running service can grow until it exhausts the heap, which is why production code usually caps the size and evicts entries with a least recently used (LRU) policy. Recursion depth is a second limit: a top-down solution for n = 100,000 may overflow the call stack where an iterative version would not.
The table summarizes frequent mistakes, how they show up and how experienced developers correct them.
| Mistake | Symptom | Fix |
|---|---|---|
| Caching an impure function | Stale or inconsistent results | Memoize only deterministic code |
| Mutable arguments as keys | Wrong hits or hashing errors | Convert to immutable tuples or IDs |
| Unbounded cache size | Steady memory growth | Set a size limit with LRU eviction |
| Deep recursion | Stack overflow on large inputs | Switch to bottom-up tabulation |
| Shared cache across threads | Race conditions or duplicate work | Use locking or per-thread caches |
A final pitfall is memoizing cheap functions. When the computation costs less than hashing the arguments and probing the table, the cache makes the program slower. Memoization pays off only when the hit rate is high and each miss is expensive.
A plain-language summary
Memoization means a program remembers answers it has already worked out. Imagine a student who solves a long math problem and writes the answer in a notebook. The next time the same problem appears, the student simply looks it up instead of solving it again.
This makes programs much faster when they keep asking the same questions. The price is the notebook itself: it takes up space, and it only works if the answer to a question never changes over time.
An example from practice
A logistics developer writes a route-pricing function that finds the cheapest way to split a shipment of 500 kilograms across trucks of several capacities. The first recursive version explores every combination and takes more than a minute for a single quote, because it recalculates the best price for the same remaining weight thousands of times.
The developer adds memoization keyed on the remaining weight and the set of available truck types. The number of distinct states falls to a few thousand, each computed once, and a quote now returns in under 50 milliseconds. Because the price table changes daily, the cache is cleared whenever new rates are loaded, which keeps the function pure for the lifetime of each cache and prevents stale quotes.