Sub topic 2
Spotting overlapping subproblems
This chapter assumes you can write recursive functions in Python, read Big-O notation, and use dictionaries and collections.Counter. The goal is to recognize, before you write any caching code, whether a recursive solution keeps solving the same smaller problem again and again.
What "overlapping" means
A recursive solution splits a problem into subproblems. The subproblems overlap when different branches of the recursion ask for the same subproblem. When that happens, plain recursion redoes work it has already done, and the cost grows with the number of calls, not with the number of distinct questions asked.
Naive Fibonacci is the standard example:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)Both fib(n - 1) and fib(n - 2) eventually need fib(n - 3), and each computes it separately.
Measuring the overlap
Don't guess. Instrument the function and count how often each argument appears.
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)
for n in sorted(calls):
print(n, calls[n])
print("distinct subproblems:", len(calls))
print("total calls:", sum(calls.values()))Output:
0 34
1 55
2 34
3 21
4 13
5 8
6 5
7 3
8 2
9 1
10 1
distinct subproblems: 11
total calls: 177There are only 11 distinct questions, but the function makes 177 calls. The call counts are themselves Fibonacci numbers, so the total grows roughly like 1.618ⁿ. For fib(40), about 331 million calls answer 41 distinct questions.
When subproblems do not overlap
Not every recursive algorithm qualifies. Merge sort splits a list into two halves, and the halves share no elements. No subproblem is ever asked for twice, so a cache would only use memory. Binary search follows a single branch, so it has nothing to overlap either.
| Algorithm | Subproblems | Overlap? |
|---|---|---|
| Naive Fibonacci | `fib(n-1)`, `fib(n-2)` | Yes, heavily |
| Grid path counting | `paths(r-1, c)`, `paths(r, c-1)` | Yes |
| Merge sort | Left half, right half (disjoint) | No |
| Binary search | One half only | No |
Overlap is what separates dynamic programming from plain divide and conquer.
Signs to look for
You can often spot overlap from the function signature, without running anything:
- The arguments that change between calls are a few small integers or indices, such as
n,i,j, or a remaining capacity. - Each argument has a limited range, so the number of distinct argument combinations is small. For example,
0..nfor one index, or(m+1)(n+1)pairs for two. - The function branches into two or more recursive calls whose arguments shrink by small, fixed steps. Different branches then land on the same values.
- The function is pure: its result depends only on its arguments and not on any outside state that changes.
The last point matters. If a call's result depends on a list that the recursion mutates, two calls with the same arguments may need different answers, and you cannot reuse results until you make that hidden state part of the arguments.
Exercises
Exercise
The function paths(r, c) counts the ways to walk from (0, 0) to (r, c) moving only right or down: it returns 1 if r == 0 or c == 0, and otherwise returns paths(r - 1, c) + paths(r, c - 1). Does it have overlapping subproblems, and how many distinct subproblems does paths(r, c) involve?
Show answer
Yes. Both paths(r - 1, c) and paths(r, c - 1) eventually call paths(r - 1, c - 1), and the sharing compounds deeper down. The distinct subproblems are all pairs (i, j) with 0 ≤ i ≤ r and 0 ≤ j ≤ c, so there are (r + 1)(c + 1) of them. The number of calls grows exponentially.
Exercise
A function total(lst) returns lst[0] + total(lst[1:]) and returns 0 for an empty list. Would caching its results speed it up? Explain using the distinct-versus-total-calls test.
Show answer
No. Each call makes exactly one recursive call, so there are n + 1 calls for a list of length n, and each call asks a different question. Distinct subproblems equal total calls, so nothing overlaps and a cache would only add memory overhead.