Memoization
Мемоизация
Memoization saves a function’s result so that the next call with the same inputs can reuse it instead of doing the work again.
The idea
Suppose a program repeatedly asks how many routes lead from a given square to the end of a grid. Once the program knows the answer for that square, it can keep the answer rather than count those routes again. That is memoization: spending memory to avoid repeated computation. The first call for a key still has to do the work, so memoization pays off only when enough later calls reuse results.
What makes a good cache key?
The key must identify everything that affects the result. For the grid problem, a row and column are enough if the grid and the movement rules stay fixed for the lifetime of the cache. If the same cache serves different grids, coordinates alone can return the wrong answer. You could scope the cache to one grid or include a grid version in the key.
On a cache hit, return the stored result. On a miss, compute it, store it, and return it. If you write the lookup yourself, test whether the key is present rather than whether the value is truthy: zero might be exactly the answer you want. Pure functions are good candidates because nothing needs to happen on a call besides producing the result. Skipping the body of a function that also sends a notification, for instance, changes its behavior.
Example: counting grid paths
The function below counts paths from (0, 0) to (r, c) in an obstacle-free grid, moving only down or right. The inputs are nonnegative integers.
from functools import cache
@cache
def paths(r, c):
if r == 0 or c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
For paths(2, 2), both branches need paths(1, 1). The first computes it; the second reuses it. Starting with an empty cache, there are at most (r + 1)(c + 1) distinct states and at most two recursive calls per state on a miss. Under constant-time arithmetic and average constant-time cache lookups, that gives an O((r + 1)(c + 1)) time bound. The cache can hold that many entries, and the recursion stack can grow to O(r + c + 1) frames.
Where it fits and what to say in interviews
Memoization is a form of caching focused on reusing computed results. It works for ordinary functions as well as recursive ones. In dynamic programming, the recursive approach is called top-down: it computes states as needed. Bottom-up tabulation fills states in dependency order instead. For this grid, a bottom-up solution can reuse one row of results and avoid recursion entirely.
When explaining a solution in an interview, start with the state and point out where two branches request the same state. Then account for the cost of processing each state, the cache, and the call stack. In application code, also consider how long entries live. An unbounded cache can keep growing when most inputs are unique; a bounded cache limits memory at the cost of occasionally having to recompute a result.