Sub topic 17
When Subproblems Overlap: Divide and Conquer Versus Dynamic Programming
This chapter assumes you can trace recursive functions, read a recurrence such as T(n) = 2T(n/2) + O(n), and follow the merge sort and maximum subarray chapters. Divide and conquer and dynamic programming both break a problem into smaller instances of the same problem. They differ in one structural property: whether those smaller instances repeat.
Disjoint Versus Overlapping Subproblems
In merge sort, the left half and the right half share no elements. Every recursive call works on a slice that no other call will ever see again. The subproblems are disjoint, so each one is solved exactly once. You get that without any bookkeeping.
Many recursive definitions do not split the input this cleanly. The Fibonacci numbers satisfy F(n) = F(n−1) + F(n−2). Both branches ask about almost the same input, and their own branches ask about it again. These subproblems are overlapping. A plain recursive solution solves the same subproblem many times.
Measuring the Waste
Count the calls the naive version makes:
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20), calls) # 6765 21891Only 21 distinct subproblems exist (fib(0) through fib(20)), but the function makes 21,891 calls. The recurrence T(n) = T(n−1) + T(n−2) + O(1) grows like φⁿ, where φ ≈ 1.618. The master theorem does not apply here. It needs subproblems of size n/b, and these shrink by subtracting 1 or 2 rather than by dividing.
The gap between the number of distinct subproblems and the number of calls is the test that matters. When those two counts are close, divide and conquer is the right fit. When the call count is far larger, you are paying again and again for answers you already computed.
Dynamic Programming: Solve Each Subproblem Once
Dynamic programming (DP) keeps the same recursive structure and adds a table of answers. There are two standard ways to fill it.
Top-down with memoization
Memoization is caching a function's return value keyed by its arguments. In Python, functools.lru_cache does this for you:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(90)) # 2880067194370816120
print(fib_memo.cache_info().misses) # 91Each value from 0 to 90 is computed once, which is 91 cache misses. The running time drops from exponential to O(n).
Bottom-up tabulation
Tabulation fills the table in an order where every dependency is ready before it is needed. No recursion is involved:
def fib_table(n):
if n < 2:
return n
prev, cur = 0, 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return cur
print(fib_table(90)) # 2880067194370816120Because F(n) depends only on the previous two values, the table shrinks to two variables. That gives O(n) time and O(1) space.
Why Memoizing Merge Sort Does Nothing
You could wrap merge sort in a cache, but no call would ever hit it. Every slice it sorts is a distinct range of the input, so the cache only adds memory and hashing cost. Memoization pays off only when the same subproblem actually repeats.
The reverse mistake also happens. Some problems that look like divide and conquer have a faster DP solution. The maximum subarray chapter used a split at the midpoint plus a crossing case, which runs in O(n log n). Kadane's algorithm solves the same problem in O(n). It asks a smaller, overlapping question at each index: what is the best sum of a subarray that ends exactly here?
def max_subarray_dp(a):
best_ending_here = best = a[0]
for x in a[1:]:
best_ending_here = max(x, best_ending_here + x)
best = max(best, best_ending_here)
return best
print(max_subarray_dp([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6The divide-and-conquer version is still worth knowing. It parallelizes naturally, and its crossing-case technique carries over to problems such as closest pair. For a sequential scan, though, the DP formulation is faster.
Side-by-Side Comparison
| Property | Divide and conquer | Dynamic programming |
|---|---|---|
| Subproblem structure | Disjoint, usually a constant fraction of the input | Overlapping, often shrinking by a constant amount |
| Times each subproblem is solved | Once, without extra effort | Once, because a table enforces it |
| Typical analysis tool | Recurrence, recursion tree, master theorem | Number of states × work per state |
| Extra memory | Recursion stack plus combine buffers | Table of all states, sometimes reducible |
| Examples | Merge sort, binary search, Karatsuba | Fibonacci, edit distance, knapsack, Kadane |
| Parallelism | Independent halves run concurrently | Limited by dependencies between states |
Deciding Which to Use
A practical way to check: write the recursion, then list the distinct argument tuples it can be called with. If that set is polynomial in size but the call tree is exponential, use DP. If the arguments are disjoint ranges that halve each time, use divide and conquer.
Common Errors and Gotchas
- Memoizing on unhashable arguments.
lru_cacheraisesTypeErrorif you pass a list. Pass indices(lo, hi)or a tuple instead. Passing indices also avoids copying slices. - Hidden state in the key. If the result depends on a global or on a mutable object that is not part of the key, the cache returns stale answers.
- Recursion depth in top-down DP. Calling
fib_memo(5000)on a cold cache recurses about 5000 levels deep. That exceeds CPython's default limit of 1000 and raisesRecursionError. Divide and conquer rarely hits this, because halving gives depth O(log n). Linear-shrinking DP needs depth O(n). Tabulation avoids the problem entirely. - Memory blow-up. A DP table over two parameters of size n uses Θ(n²) memory. Look at which earlier rows each state actually reads. Often you only need to keep one or two of them.
- Assuming optimal substructure. DP is correct only if an optimal answer is built from optimal answers to its subproblems. Longest simple path in a general graph fails this test. Caching does not make an incorrect recurrence correct.
Exercises
Exercise
The binomial coefficient satisfies C(n, k) = C(n-1, k-1) + C(n-1, k), with C(n, 0) = C(n, n) = 1. Are its subproblems disjoint or overlapping, and how many distinct subproblems does computing C(n, k) involve?
Show answer
They overlap. C(n-1, k-1) and C(n-1, k) both depend on C(n-2, k-1). The distinct subproblems are pairs (i, j) with 0 ≤ i ≤ n and 0 ≤ j ≤ k, so there are O(nk) of them. Memoization or tabulation computes C(n, k) in O(nk) time, while the plain recursion makes about 2·C(n, k) − 1 calls, which can be exponential in n.
Exercise
A colleague adds @lru_cache to a merge sort that takes (lo, hi) indices into a shared list and sorts that range in place. What happens to the running time, and is the result still correct?
Show answer
The running time stays O(n log n) plus hashing overhead, because every (lo, hi) range is visited exactly once and the cache never hits. The output is still correct, but only because nothing repeats. The function works by mutating a shared list, so if a call ever did repeat, the cache would skip the in-place work and the list would be left partly unsorted.
Exercise
Why does top-down memoized Fibonacci risk RecursionError for n = 5000 while merge sort on 5000 elements does not?
Show answer
Memoized Fibonacci reduces n by 1 per level, so its first descent is about 5000 calls deep, which exceeds CPython's default limit of 1000. Merge sort halves the input at each level, so its depth is about log2(5000) ≈ 13.