Memoizing a Recursive Function
Memoization saves a finished answer under the state that produced it and reuses that answer for later requests for the same state.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace the first reuse
If a recursive count from five reaches the state two through several branches, only the first request needs to calculate two. Later requests read its answer. A dictionary cache needs the full recursive state as its key.
Account for outstanding work
A cache of finished answers alone does not make a cyclic recursive dependency safe. A state can request itself again before its first answer is stored. See visited states for reachability tasks and choose a method suitable for cycles.[1]
Show which request becomes a cache hit
A small path counter follows grid steps right and down toward a fixed goal. Routes from the start can reach coordinate \((1,1)\) via two prefixes. Once the suffix count is known for that coordinate, both prefixes can use it. The goal and grid must remain fixed or enter the cache key.
Prefix A: (0,0) → (1,0) → (1,1)
Prefix B: (0,0) → (0,1) → (1,1)
First request at (1,1): compute suffix count
Second request at (1,1): reuse that count
Distinguish unavailable from a valid zero result
An obstacle can leave a state with zero routes. Storing that zero avoids repeating the search, provided the cache tests presence rather than truthiness. Time and memory still depend on the number of distinct states reached. A cycle requires separate handling because a result might be requested before its first computation completes.