Reuse Overlapping Subproblems with Memoization
Core idea
Memoized recursion caches answers for repeated states. For counting paths along a row using steps of one or two, ways(n)=ways(n-1)+ways(n-2), with ways(0)=1 and ways(n<0)=0. There are O(n) distinct states for nonnegative n, giving O(n) additions and O(n) retained values plus recursion frames. This counts arithmetic operations, not big-integer bit costs.
from functools import cache@cachedef ways(n): if n == 0: return 1 if n < 0: return 0 return ways(n-1)+ways(n-2)print(ways(5))print(ways.cache_info().misses)States -1 through 5 are computed once.
Inspect repeated requests
from functools import cache@cachedef square(n): return n*nsquare(4)square(4)print(square.cache_info().hits)The second identical request reuses the saved value.
Common mistake
Cache keys must capture every input that affects the answer; cached functions should not depend on changing hidden state. An unbounded cache can retain many values, and recursion still has a depth limit.
Practice
Change allowed steps to 1 and 3. Derive new base cases and compare cache misses for n=8.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memoized recursion
Check your understanding of memoized recursion.
What is printed?
from functools import cache@cachedef f(x): return x+1f(2);f(2)print(f.cache_info().misses)What is printed?
print(1+1)What gives memoization a speed advantage?
What remains despite caching?