Sub topic 1
From recursion to repeated work
Dynamic programming (DP) starts with a recursive solution that is correct but slow. This chapter takes that starting point apart. You will write a plain recursive function, measure how much work it does, and find where that work goes. By the end, you will be able to say exactly why the function is slow, and you will have the numbers to show it. Later chapters give the fixes, memoization and tabulation.
Prerequisites
This chapter assumes you can already do the following:
- Write Python functions, loops, and conditionals.
- Read and write recursive functions with base cases.
- Use lists, nested lists, dictionaries, and sets.
- Use Big-O notation to describe how running time and memory grow with input size.
You do not need any earlier exposure to dynamic programming.
Recursive decomposition in one paragraph
A recursive solution states a problem in terms of smaller copies of itself. It has two parts. The base cases are inputs small enough to answer directly. The recursive case combines answers to smaller inputs into the answer for the current input. Correctness follows from induction: if the base cases are right and every recursive call moves toward a base case, the function returns the right answer for every input.
This way of thinking is the foundation of DP. A DP solution is a recursive decomposition plus a decision to never solve the same smaller problem twice. To see why that decision matters, look at what happens without it.
The classic example: Fibonacci
The Fibonacci numbers are defined by F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2) for n ≥ 2. The definition translates directly into code:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]This function is correct and easy to verify against the definition. It is also very slow. fib(30) takes a noticeable fraction of a second, fib(35) takes several seconds on a typical laptop, and fib(50) would run for hours. Each extra 1 added to n multiplies the running time by about 1.6.
The arithmetic is cheap: one addition per call. The cost comes from the number of calls.
Drawing the call tree
Each call to fib(n) with n ≥ 2 makes two more calls. Drawing every call as a node gives a call tree. Here is the tree for fib(5):
The tree has 15 nodes but only 6 distinct inputs: 0 through 5. The whole fib(3) subtree is computed twice, fib(2) three times, and fib(1) five times. Every repeated subtree returns the same value it returned the first time, so all of that work is thrown away.
Measuring the repeated work
The tree for fib(5) is small enough to count by hand. For larger inputs, add a counter to the function itself:
from collections import Counter
calls = Counter()
def fib(n):
calls[n] += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
result = fib(10)
print("fib(10) =", result)
for k in sorted(calls, reverse=True):
print(f"fib({k}) called {calls[k]} times")
print("total calls:", sum(calls.values()))
print("distinct inputs:", len(calls))Running it prints:
fib(10) = 55
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 times
total calls: 177
distinct inputs: 11The call counts are themselves Fibonacci numbers. fib(k) is called F(n − k + 1) times when you start from fib(n), for k ≥ 1. The total number of calls is 2·F(n + 1) − 1. Since F(n) grows like φⁿ, where φ ≈ 1.618 is the golden ratio, the running time is Θ(φⁿ). That is exponential.
The distinct-input count grows much more slowly: n + 1. The table below shows the gap.
| n | Distinct inputs | Total calls | Calls per distinct input |
|---|---|---|---|
| 5 | 6 | 15 | 2.5 |
| 10 | 11 | 177 | 16.1 |
| 20 | 21 | 21,891 | 1,042 |
| 30 | 31 | 2,692,537 | 86,856 |
At n = 30, the function does about 87,000 calls' worth of work for each answer it actually needs. If each distinct input were solved only once, the cost would be 31 calls.
Timing it
Call counts explain the slowdown, and a timer confirms it:
import time
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in range(20, 33, 3):
start = time.perf_counter()
fib(n)
elapsed = time.perf_counter() - start
print(f"n={n:2d} {elapsed:.4f} s")Your exact times will vary by machine. The pattern does not: each step of 3 in n multiplies the time by about φ³ ≈ 4.2. An exponential curve like this can't be fixed by a faster computer or a faster language. A machine 100 times faster only lets you go about 10 values of n further.
It is not just Fibonacci
Fibonacci is the standard example because it is short, but the same pattern shows up in many recursive solutions. Here is a second one. Count the paths from the top-left cell to the bottom-right cell of an r × c grid, moving only right or down. The last move into the bottom-right cell came either from above or from the left, so:
- paths(r, c) = paths(r − 1, c) + paths(r, c − 1)
- paths(1, c) = paths(r, 1) = 1, because a single row or column has one path.
calls = 0
distinct = set()
def paths(r, c):
global calls
calls += 1
distinct.add((r, c))
if r == 1 or c == 1:
return 1
return paths(r - 1, c) + paths(r, c - 1)
print("paths(10, 10) =", paths(10, 10))
print("total calls:", calls)
print("distinct inputs:", len(distinct))The output:
paths(10, 10) = 48620
total calls: 97239
distinct inputs: 99The input now has two parameters, but the problem is the same. There are at most r × c distinct inputs, yet the call tree has one leaf for every path. The number of paths grows exponentially as the grid gets bigger. The two calls paths(r − 1, c) and paths(r, c − 1) both eventually reach paths(r − 1, c − 1), and from there every shared sub-grid is recomputed along every route that reaches it.
When recursion does not repeat work
Not every recursive function wastes effort. Merge sort splits a list into two halves, sorts each, and merges them. The two halves don't overlap, so no sublist is ever sorted twice. The call tree has O(n) nodes, and each level does O(n) merging work, for O(n log n) total. Adding a cache to merge sort would only cost memory.
The difference is in how the subproblems relate:
| Pattern | Subproblems | Example | Cost of naive recursion |
|---|---|---|---|
| Divide and conquer | Disjoint; each solved once | Merge sort, binary search | Usually polynomial |
| Overlapping | The same input is reached by many paths | Fibonacci, grid paths | Often exponential |
The useful question to ask about any recursive solution is "how many distinct inputs can this function ever receive, and how many calls does it actually make?" If the second number is far larger than the first, the function is repeating work, and DP can remove the repetition.
Common errors at this stage
- Blaming the arithmetic. The additions in
fibare cheap. The cost is the number of calls. Faster arithmetic won't help. - Blaming recursion itself. Python recursion has overhead, but merge sort shows that recursion can be efficient. Exponential time comes from repeated subproblems, not from recursion.
- Confusing recursion depth with call count.
fib(30)never goes deeper than 30 frames on the call stack, yet it makes over 2.6 million calls. Depth limits memory on the stack. Call count drives time. - Using a mutable global counter carelessly. In the instrumented examples, run each measurement in a fresh process or reset the counter before every call. Otherwise counts from earlier runs pile up.
What comes next
You now have a working diagnosis. The naive recursion is correct, the number of distinct subproblems is small, and the slowness comes from solving the same subproblems again and again. The next chapters name this property, overlapping subproblems, and pair it with optimal substructure. Together they turn the diagnosis into a method.
Exercise
Without running code, how many total calls does the naive fib(6) make, and how many times is fib(2) called?
Show answer
Total calls are 2·F(7) − 1 = 2·13 − 1 = 25. fib(2) is called F(6 − 2 + 1) = F(5) = 5 times.
Exercise
The recursive depth of the naive fib(40) is about 40 frames, yet it takes a long time to finish. Explain why the depth and the running time differ so much.
Show answer
Depth measures the longest chain of nested calls, which is n because each call reduces n by at least 1. Running time depends on the total number of calls in the whole tree, which is 2·F(41) − 1, about 330 million. The stack only ever holds one path through the tree at a time, but the function visits every node.
Exercise
A function countways(n) returns the number of ways to climb n stairs taking 1, 2, or 3 steps at a time, using countways(n) = countways(n-1) + countways(n-2) + countways(n-3), with countways(0) = 1 and count_ways(n) = 0 for n < 0. How many distinct inputs can it receive when started at n, and is its naive call count polynomial or exponential?
Show answer
Inputs range from n down to −2, so there are n + 3 distinct inputs. Each call branches three ways and the branches share sub-inputs, so the call count grows exponentially (roughly like 1.84ⁿ). It repeats work heavily and is a good candidate for DP.
Exercise
Binary search is recursive. Would caching its results by (low, high) speed it up? Explain using the distinction from this chapter.
Show answer
No. Each binary search call makes only one recursive call on a disjoint half, so no (low, high) pair is ever visited twice. There is no repeated work to remove, and a cache would only add memory and lookup overhead.