On this page · Identify the Whole Remaining Question
Memoization
Cache completed answers under a key that identifies the whole remaining subproblem. Reuse overlapping states without treating a valid zero result as a cache miss.
Recognize it when Recursive branches repeatedly reach the same remaining state.
Checking your account…
Memoization Code Labs
Identify the Whole Remaining Question
Two recursive calls may share a cached answer only when their future choices and costs agree. A row alone is not a complete key for a grid: two columns in that row can have different paths to the destination. For a fixed read-only grid with right/down movement, the pair (row,col) is sufficient because the prefix path no longer changes the remaining cost.
See When Hits and Completions Are Recorded
The Fibonacci trace starts with completed base answers 0 and 1. A hit records immediately on lookup. A new state records only after its two recursive dependencies return. Consequently the output is event execution order, not the entry order of every function call.
Trace Memoized Calls
Reference
def memo_fibonacci_trace(n):
cache={0:0,1:1};events=[]
def solve(value):
if value in cache:events.append([value,True,cache[value]]);return cache[value]
result=solve(value-1)+solve(value-2);cache[value]=result;events.append([value,False,result]);return result
solve(n);return events
Practice
Implement memo_fibonacci_trace(n) for a nonnegative integer n. Return [state,cache_hit,value] events in execution order: hits at lookup and new states after their dependencies complete.
Public tests
Reuse completed states
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Memoized Calls
def memo_fibonacci_trace(n):
cache={0:0,1:1};events=[]
def solve(value):
if value in cache:events.append([value,True,cache[value]]);return cache[value]
result=solve(value-1)+solve(value-2);cache[value]=result;events.append([value,False,result]);return result
solve(n);return events
Separate Lookup Events from Completed States
Predict memo_fibonacci_trace(3). The entry into solve(3) creates no event until its dependencies are complete.
Step
Executed statement
State
Why
1
result=solve(value-1)+solve(value-2)
solve(3) enters solve(2); cache={0:0,1:1}
The first missing state must obtain both smaller answers.
2
events.append([value,True,cache[value]])
events=[[1,True,1],[0,True,0]]
Both bases are present, including the valid zero answer.
Testing key in cache preserves a cached zero as a hit. A truthiness check such as cache.get(key) cannot distinguish a present zero from an absent key. Python dictionaries need hashable keys; a tuple of integers works, while a list of coordinates raises TypeError.
Solve the Grid Recurrence Once per Coordinate
minimum_path_cost accepts a nonempty rectangular numeric grid. The bottom-right cell contributes its own cost. At every other coordinate, take the cheaper legal right/down suffix and add the current cell. Movement strictly increases a coordinate, so dependencies cannot cycle; after they return, the combined result is final and safe to cache.
Memoize Minimum Grid Path Cost
Reference
def minimum_path_cost(grid):
cache={}
def solve(row,col):
if row==len(grid)-1 and col==len(grid[0])-1:return grid[row][col]
if (row,col) in cache:return cache[(row,col)]
best=float("inf")
if row+1<len(grid):best=min(best,solve(row+1,col))
if col+1<len(grid[0]):best=min(best,solve(row,col+1))
cache[(row,col)]=grid[row][col]+best;return cache[(row,col)]
return solve(0,0)
Practice
Implement minimum_path_cost(grid) for a nonempty rectangular numeric grid. Move only right or down from top-left to bottom-right and return the minimum cell sum.
Public tests
Cache the complete row-column state
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Memoize Minimum Grid Path Cost
def minimum_path_cost(grid):
cache={}
def solve(row,col):
if row==len(grid)-1 and col==len(grid[0])-1:return grid[row][col]
if (row,col) in cache:return cache[(row,col)]
best=float("inf")
if row+1<len(grid):best=min(best,solve(row+1,col))
if col+1<len(grid[0]):best=min(best,solve(row,col+1))
cache[(row,col)]=grid[row][col]+best;return cache[(row,col)]
return solve(0,0)
Negative cell costs do not break this recurrence because no cell can be revisited. The grid remains unchanged. Terminal cells can be returned directly without caching because they perform constant work.
Compare Top Down and Bottom Up in an Interview
The grid has O(RC) states with at most two transitions each, giving O(RC) time and cache space. Its deepest dependency chain is O(R+C), so memoization removes repeated work but does not remove recursion depth. Tabulation uses a deliberate dependency order and can compress dead rows when only the final cost is needed. Choose memoization for a natural recurrence or sparse reachable states; choose tabulation when depth or predictable iteration matters. The same selection rule applies beyond this grid example.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Top-down DP (recursion + cache)
Write the recursion first, then cache it.
A recursive solution recomputes the same subproblems; the parameters of the recursion are the state.
Trigger words
word break
recursion repeats
longest increasing path
@cache
try every split
from functools import cache
def unique_paths(rows, cols):
@cache
def ways(r, c):
if r == rows - 1 and c == cols - 1:
return 1 # reached the target
if r >= rows or c >= cols:
return 0 # fell off the grid
return ways(r + 1, c) + ways(r, c + 1)
return ways(0, 0)
Spot it when
The brute-force recursion is easy to write but exponential.