Sub topic 10
Top-Down Interval DP with Memoization
This chapter assumes you already know the split-point recurrence, the endpoint-shrinking recurrence, and the bottom-up length-ordered table from earlier chapters. It also assumes you are comfortable with Python closures and functools.lru_cache. The chapter writes the same recurrences as recursive functions with a cache. It covers what you gain by doing that, what it costs, and the errors that come up most often.
Why Write It Top-Down at All
A bottom-up interval DP makes you pick an evaluation order before you write any code. For the simple recurrences, "increasing length" or "i downward, j upward" works. A top-down version skips that step. You write the recurrence almost exactly as you would state it mathematically. The recursion then computes each dependency the first time it is needed, so the order comes out right without you planning it.
This helps most in three cases:
- The recurrence is new and you want to check that it is correct before you tune it.
- The order of dependencies is awkward, for example when the state has a third dimension or the transitions jump around.
- Many states can never be reached from the starting call, so the recursion never touches them.
For plain two-index interval problems, the starting call usually reaches almost all of the O(n²) states. In that case top-down saves no work. It is just easier to write.
The Shape of a Memoized Interval Function
Each top-down interval DP has four parts:
- A function
best(i, j)whose arguments are exactly the interval bounds. - Base cases checked first: empty or single-element intervals.
- A cache lookup, so each
(i, j)is computed at most once. - The transition: loop over split points, or compare endpoints, and recurse on smaller intervals.
Here is matrix chain multiplication written this way. Matrix i has shape dims[i] x dims[i + 1], and best(i, j) is the minimum cost to multiply matrices i through j inclusive.
from functools import lru_cache
def matrix_chain_top_down(dims):
n = len(dims) - 1
if n <= 0:
return 0
@lru_cache(maxsize=None)
def best(i, j):
if i == j:
return 0
return min(
best(i, k) + best(k + 1, j) + dims[i] * dims[k + 1] * dims[j + 1]
for k in range(i, j)
)
return best(0, n - 1)
print(matrix_chain_top_down([10, 30, 5, 60])) # 4500The body is the split recurrence and nothing else. The function contains no loop over lengths, so you cannot get the fill order wrong.
The same thing with an explicit table
lru_cache is convenient, but an explicit memo table gives you control over memory and lets you inspect the table afterward. Use a sentinel value that no real answer can take.
def matrix_chain_memo(dims):
n = len(dims) - 1
if n <= 0:
return 0
memo = [[None] * n for _ in range(n)]
def best(i, j):
if i == j:
return 0
if memo[i][j] is not None:
return memo[i][j]
result = float("inf")
for k in range(i, j):
cost = best(i, k) + best(k + 1, j) + dims[i] * dims[k + 1] * dims[j + 1]
if cost < result:
result = cost
memo[i][j] = result
return result
return best(0, n - 1)
print(matrix_chain_memo([10, 30, 5, 60])) # 4500To record split points for reconstruction, store k in a second table next to memo[i][j], exactly as the bottom-up version does.
What the Cache Actually Saves
Without the cache, the split recurrence takes exponential time, because the same subintervals are solved again inside different splits. The diagram shows the calls for three matrices. best(1,1) and the other single-matrix intervals are reached along more than one path.
You can count the calls directly. The function below leaves out the cost term because only the number of calls matters here.
def count_calls(n, memoize):
calls = 0
memo = {}
def best(i, j):
nonlocal calls
calls += 1
if i == j:
return 0
if memoize and (i, j) in memo:
return memo[(i, j)]
result = min(best(i, k) + best(k + 1, j) for k in range(i, j))
if memoize:
memo[(i, j)] = result
return result
best(0, n - 1)
return calls
print(count_calls(10, memoize=False)) # 19683
print(count_calls(10, memoize=True)) # 331Without the cache, the call count satisfies T(n) = 1 + 2·(T(1) + … + T(n−1)), which solves to 3ⁿ⁻¹. With the cache, each interval of length L ≥ 2 is expanded once and makes 2(L−1) calls. That totals O(n³) calls, the same bound as the bottom-up loops.
Endpoint-Shrinking Recurrences Top-Down
Endpoint recurrences translate the same way. With inclusive bounds, an empty interval appears as i > j, and you must handle it explicitly.
from functools import lru_cache
def lps_top_down(s):
@lru_cache(maxsize=None)
def best(i, j):
if i > j:
return 0
if i == j:
return 1
if s[i] == s[j]:
return best(i + 1, j - 1) + 2
return max(best(i + 1, j), best(i, j - 1))
return best(0, len(s) - 1)
print(lps_top_down("bbbab")) # 4If you leave out the i > j check, a two-character match such as "aa" calls best(1, 0). That call falls through to s[1] == s[0] and recurses to best(2, -1), which reads s[-1] and silently returns a wrong result. Bottom-up code avoids this because the table defaults to 0. Top-down code has no table cell to fall back on, so the empty case has to be written out.
Common Errors
Unhashable arguments
lru_cache hashes every argument. If you pass the list itself, as in best(dims, i, j), you get TypeError: unhashable type: 'list'. Capture the data in a closure, as above, or convert it to a tuple once. Keep only the interval bounds as arguments.
Stale caches across calls
A cached function defined at module level that reads a global sequence keeps its cache between test cases. The second input then gets the first input's answers. Define the cached function inside the outer function so that each call gets a new cache. Otherwise, call best.cache_clear() between runs.
Sentinel collisions
With an explicit table, 0 or -1 as "not computed" breaks whenever a real answer can equal that value. With 0, the code still gives correct answers but recomputes those states, which can bring back exponential time. With -1 in a problem that allows negative scores, it gives wrong answers. Use None, or keep a separate boolean "computed" table.
Recursion depth
Every recursive call shrinks the interval by at least one, so the recursion depth is at most about n. That is fine for n of a few hundred. CPython's default limit is 1000 frames, though, and lru_cache adds overhead to each frame. For larger inputs, raise the limit and run the computation on a thread with a bigger stack:
import sys
import threading
from functools import lru_cache
def lps_top_down(s):
@lru_cache(maxsize=None)
def best(i, j):
if i > j:
return 0
if i == j:
return 1
if s[i] == s[j]:
return best(i + 1, j - 1) + 2
return max(best(i + 1, j), best(i, j - 1))
return best(0, len(s) - 1)
def run_with_big_stack(fn, *args):
sys.setrecursionlimit(100_000)
threading.stack_size(256 * 1024 * 1024)
result = []
worker = threading.Thread(target=lambda: result.append(fn(*args)))
worker.start()
worker.join()
return result[0]
print(run_with_big_stack(lps_top_down, "ab" * 600)) # 1199Exclusive bounds
Some problems read more naturally with an open interval (left, right). Burst balloons, covered in a later chapter, is one example. In that form the empty interval is right - left < 2. A split loop range(left + 1, right) then has no iterations, and the function returns its initial value of 0, so the base case is implicit. When you write the function, decide which convention you are using and check that the starting call matches it. For example, an inclusive function starts with best(0, n - 1), while an exclusive one over padded values starts with best(0, len(vals) - 1).
Choosing Between Top-Down and Bottom-Up
| Concern | Top-down memoized | Bottom-up by length |
|---|---|---|
| Ordering dependencies | Automatic | You must derive it |
| States computed | Only reachable ones | All of them |
| Constant factor in Python | Higher (calls, hashing) | Lower (plain loops) |
| Stack depth | Up to about n frames | None |
| Memory layout | Hash map or table | Dense table |
| Applying Knuth's optimization | Awkward | Natural |
| Prototyping a new recurrence | Easiest | More bookkeeping |
A practical workflow has three steps. First, write the top-down version to confirm the recurrence on small inputs. Then convert it to bottom-up if speed, stack depth, or an optimization needs a fixed fill order. Finally, keep the top-down version as a reference and check that the two agree on random inputs.
Exercise
A memoized function best(i, j) uses an explicit table initialized to 0 to mean "not computed". It solves a minimum-cost problem where many intervals truly have cost 0. Is the answer still correct, and what happens to the running time?
Show answer
The answer stays correct, because a state whose value is 0 is simply recomputed and gives the same result. The running time can blow up, though. Each zero-cost state is expanded again every time it is reached, so the overlapping subproblems are no longer shared and the work can become exponential. Use None or a separate computed flag.
Exercise
Write a memoized function min_merge(piles) for merging adjacent piles, where merging piles i..j always costs their total weight at the final step. Use inclusive bounds and prefix sums. What does it return for [4, 1, 1, 4]?
Show answer
Build prefix sums so the total of piles i..j is prefix[j + 1] - prefix[i]. Define best(i, j) as 0 when i == j, otherwise as min over k in range(i, j) of best(i, k) + best(k + 1, j), plus that interval total. Cache best with lrucache inside minmerge and return best(0, n - 1), or 0 when n <= 1. For [4, 1, 1, 4] it returns 20.
Exercise
For n = 5 matrices, how many calls does the unmemoized split recursion make, and how many does the memoized version make?
Show answer
Unmemoized: 3^(5-1) = 81 calls. Memoized: 1 + 2 times the sum over L from 2 to 5 of (6 - L)(L - 1), which is 1 + 2(4 + 6 + 6 + 4) = 41 calls.