Skip to contentKEEP THE CRAFTTHE SANCTUARY

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.

2 practice exercises2 interview problems

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.
3 cache[value]=result; events.append([value,False,result]) cache[2]=1; next event=[2,False,1] State 2 becomes reusable only after both child results return.
4 events.append([value,True,cache[value]]) next event=[1,True,1] The second dependency of 3 reuses the completed base state.
5 cache[value]=result; events.append([value,False,result]) cache[3]=2; final event=[3,False,2] Combining the two completed answers finishes state 3.
Print Output
print(memo_fibonacci_trace(3)) [[1, True, 1], [0, True, 0], [2, False, 1], [1, True, 1], [3, False, 2]]

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.
  • 'Word break', 'longest increasing path', 'target sum'.

Remember

  • The function's arguments are the DP state; the cache stores each state once.
  • Deep recursion (thousands of levels) can hit Python's recursion limit; then switch to a bottom-up table.

How problems bend it

  • Word break: State is the start index: can s[start:] be split? Try every dictionary word that matches here.
  • Grid with obstacles: Return 0 when the cell is blocked.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Memoize right/down minimum path costs on an R by C gridO(R*C)O(R*C)Each nonterminal coordinate is solved once and has at most two outgoing dependencies.

Space

O(R*C) cache plus O(R+C) call-stack depth; O(R*C) overall.

Assumptions

  • The fixed grid is shared read-only within one call; row and column therefore fully identify each remaining path-cost state.
  • Fibonacci tracing has O(n) events and stack depth under unit-cost arithmetic; growing integer bit costs are additional.
  • Dictionary and functools cache keys must be hashable; tuples of integer coordinates are suitable, lists are not.

Invariants Worth Saying Aloud

  1. A cache key identifies every dimension that changes the remaining answer.
  2. Stored values are final answers after dependencies have returned.
  3. Cache membership is separate from the truth value of the stored answer.

When To Use Or Avoid Memoization

Use It When

  • The recurrence has acyclic dependencies and repeated subproblems.
  • Only a subset of a large state space is reachable, making top-down discovery convenient.

Choose Another Tool When

  • A key omits changing context or the function reads mutable input that changes during the search.
  • Dependency cycles require active-state detection or graph analysis; caching completed results alone does not break them.
  • Deep dependency chains risk Python recursion limits; bottom-up tabulation may be safer.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Treating a cached zero as absent

A legitimate zero answer is falsy, but its key still denotes a solved state.

Prevent it: Test dictionary membership rather than the truth value of get.

Avoid

is_hit=bool(cache.get(key))

Use instead

is_hit=key in cache

Dropping a future-affecting coordinate

Using only the row can reuse a cost belonging to a different column.

Prevent it: Include both row and column for this fixed-grid subproblem.

Avoid

answer=cache[row]

Use instead

answer=cache[(row,col)]

Building an unhashable state key

A list cannot serve as a dictionary key, so cache insertion fails before reuse can happen.

Prevent it: Use a hashable tuple whose elements are also hashable.

Avoid

key=[row,col]
cache[key]=7

Use instead

key=(row,col)
cache[key]=7

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.