Sub topic 2
Spotting overlapping subproblems
This chapter assumes you can write recursive functions in Python, use dictionaries and collections.Counter, and read Big-O notation. It does not cover caching or tables yet. Its goal is narrower: to give you a reliable way to tell whether a recursive solution repeats work, and how much.
Dynamic programming pays off only when a problem has overlapping subproblems, meaning the same smaller problem comes up many times while the larger one is being solved. If every subproblem is unique, storing answers buys you nothing. So before reaching for a cache, check that there is something to cache.
What "the same subproblem" means
A subproblem is one call of your recursive function with a particular set of arguments. Two calls are the same subproblem when they are guaranteed to return the same answer. In a pure function, which depends only on its arguments, this happens exactly when the arguments are equal.
That gives a simple test. Run the recursion, record the arguments of every call, and compare two numbers:
- Total calls: how many times the function ran.
- Distinct states: how many different argument tuples appeared.
If total calls are much larger than distinct states, the subproblems overlap. The ratio between the two numbers is roughly how much work a cache could save.
Instrumenting a recursion
Here is the naive Fibonacci function with a counter keyed by its argument:
from collections import Counter
calls = Counter()
def fib(n):
calls[n] += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(10)
print("total calls:", sum(calls.values()))
print("distinct states:", len(calls))
for k in sorted(calls, reverse=True):
print(f"fib({k}) called {calls[k]} times")Output:
total calls: 177
distinct states: 11
fib(10) called 1 times
fib(9) called 1 times
fib(8) called 2 times
fib(7) called 3 times
fib(6) called 5 times
fib(5) called 8 times
fib(4) called 13 times
fib(3) called 21 times
fib(2) called 34 times
fib(1) called 55 times
fib(0) called 34 timesOnly 11 distinct questions exist (fib(0) through fib(10)), but the function answers them 177 times. The repeat counts are themselves Fibonacci numbers, so the total grows exponentially: fib(n) makes 2·F(n+1) − 1 calls. For n = 30 that comes to about 2.7 million calls covering just 31 states.
Seeing the overlap in the recursion tree
A recursion tree draws each call as a node, with an edge to each call it makes. The repeated subtrees are where the overlap lives.
Merge every node that carries the same label and the tree turns into a subproblem graph. This is a directed acyclic graph (DAG) with one node per distinct state and an edge from each state to the states it depends on. Overlap is the difference between the size of the tree and the size of the graph.
The tree has 15 nodes and the graph has 6. Later chapters show that a DP solution does work proportional to the graph rather than the tree.
A reusable call tracer
Adding a counter to every function by hand gets tedious. A decorator can record the argument tuple of each call:
from collections import Counter
from functools import wraps
def count_calls(func):
counts = Counter()
@wraps(func)
def wrapper(*args):
counts[args] += 1
return func(*args)
wrapper.counts = counts
return wrapper
def report(func):
total = sum(func.counts.values())
distinct = len(func.counts)
worst = max(func.counts.values())
print(f"total={total} distinct={distinct} "
f"ratio={total / distinct:.1f} max_repeats={worst}")The decorator rebinds the function's global name, so the recursive calls inside the body also go through wrapper and get counted.
Example: counting grid paths
How many paths run from the top-left to the bottom-right of a grid when you can only move down or right? From cell (r, c), the last step came either from above or from the left:
@count_calls
def paths(r, c):
if r == 0 or c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
print(paths(8, 8))
report(paths)Output:
12870
total=25739 distinct=80 ratio=321.7 max_repeats=3432Only 80 cells are ever visited, yet the function runs 25,739 times, and one state alone ((1, 1)) is solved 3,432 times. Here the overlap comes from many different routes passing through the same cell. That is typical of two-argument problems, and it gets worse quickly as the grid grows.
Counterexample: divide and conquer
Now take a function that splits a range in half, the way merge sort does:
data = list(range(1, 17))
@count_calls
def range_sum(lo, hi):
if hi - lo == 1:
return data[lo]
mid = (lo + hi) // 2
return range_sum(lo, mid) + range_sum(mid, hi)
print(range_sum(0, len(data)))
report(range_sum)Output:
136
total=31 distinct=31 ratio=1.0 max_repeats=1Every call covers a different range, so no state ever repeats. The subproblems are disjoint: they do not share any smaller subproblem. Caching this function would only add memory and dictionary lookups. That distinction is what separates dynamic programming from plain divide and conquer.
| Function | Total calls | Distinct states | Ratio | Overlap? |
|---|---|---|---|---|
| `fib(10)` | 177 | 11 | 16.1 | Yes, exponential |
| `paths(8, 8)` | 25,739 | 80 | 321.7 | Yes, exponential |
| `range_sum(0, 16)` | 31 | 31 | 1.0 | No |
Spotting overlap without running code
Tracing works, but you can usually predict the result from the recurrence alone. Check these signs:
- More than one recursive call that shrinks the argument by small, fixed amounts.
fib(n - 1)andfib(n - 2)both eventually reachn - 3. When the steps are small and different, the paths meet again. - Different choice orders that reach the same state. In grid paths, "down then right" and "right then down" both land on the same cell. Whenever the order of choices doesn't affect what remains, overlap follows.
- A small state space compared with the call tree. Count the possible argument values. If
nranges over0..N, there are at mostN + 1states. A branching recursion on so few states has to repeat them. - Splits into disjoint parts mean no overlap. If the recursion splits the input into non-intersecting pieces (halves, separate subtrees of a tree), expect a ratio near 1.
Edge cases that hide or fake overlap
Arguments that hide the identity of a subproblem
Code often passes slices such as solve(items[1:]). Each slice is a new list, so the subproblem's identity gets buried inside an unhashable object, and a counter keyed on arguments raises TypeError. The real state is just the start index. Rewrite the function as solve(i) with items taken from the enclosing scope, and the overlap becomes visible and countable. Slicing also costs O(n) per call, which hides the real per-call cost.
Equivalent states with different arguments
Sometimes two different argument tuples describe the same problem. In a square grid, paths(3, 5) equals paths(5, 3) by symmetry. A tracer counts them as distinct, so it understates the overlap. Putting arguments in a canonical form (for example, sorting them when order doesn't matter) shrinks the state space further. Do this only when you can prove the two states are equivalent.
Hidden state that breaks reuse
The test "same arguments means same answer" only holds for pure functions. If the function reads a global that changes during the recursion, a counter that tracks a running total, or a mutable argument that gets modified, then two calls with equal arguments can return different results. The tracer will still report repeats, but those repeats are not safe to reuse.
Overlap that is too small to matter
A ratio slightly above 1, such as a few repeats near the leaves, rarely justifies a cache. What you should look for is how the ratio grows with input size. Run the tracer at two or three sizes. If the ratio grows exponentially, dynamic programming will change the complexity class. If it stays near a constant, a cache improves speed by at most that constant.
Summary
- A subproblem is identified by its arguments. Overlap means the same arguments show up in many calls.
- Measure total calls and distinct states, then compare them. A large and growing ratio signals that dynamic programming applies.
- A recursion tree shows the repeated work. Merging identical nodes gives the subproblem graph, which is the work a DP solution actually does.
- Divide and conquer on disjoint pieces has no overlap.
- Expose the true state (indices instead of slices), and make sure the function is pure before you treat repeats as reusable.
Exercise
The function below counts the ways to climb n stairs taking 1, 2, or 3 steps at a time. Without running it, does it have overlapping subproblems? How many distinct states does ways(20) visit? Then decorate it with count_calls and check your answer. def ways(n): if n < 0: return 0 if n == 0: return 1 return ways(n - 1) + ways(n - 2) + ways(n - 3)
Show answer
Yes. Three calls shrink n by small, different amounts, so paths such as 1+2 and 2+1 both reach n-3. The arguments reached are 20 down to -2, which makes 23 distinct states (the base case returns 0 for n of -1 and -2). The tracer reports tens of thousands of total calls against those 23 states, and the ratio grows exponentially with n.
Exercise
A binary search function bsearch(lo, hi) recurses into exactly one half of the range on each call. Does it have overlapping subproblems? Would caching it help?
Show answer
No. Each call makes at most one recursive call, so the recursion tree is a single path with O(log n) nodes and no state repeats. The ratio of total calls to distinct states is exactly 1, and a cache would only add overhead.
Exercise
A recursive function solve(items) calls solve(items[1:]) and solve(items[2:]). Applying count_calls raises TypeError: unhashable type: 'list'. Explain why, and rewrite the signature so that the overlap can be measured.
Show answer
Counter keys must be hashable, and lists are not. Each slice is also a new object, so the subproblem's identity is hidden in the list contents. The only thing that varies between calls is the starting position, so rewrite it as solve(i), which reads items[i:] logically from a list in the enclosing scope and calls solve(i + 1) and solve(i + 2). The argument is now an int, and the tracer shows the same Fibonacci-like overlap with n + 1 distinct states.