Dynamic Programming
Dynamic programming is a technique that solves a complex problem by breaking it into many smaller, simpler problems, saving each answer once it is found so it can be reused later. The commonly used term DP refers to dynamic programming.
At a Glance
It is an algorithm that makes sure each distinct problem is solved only once. In other words, it prevents the same computation from being repeated. You can think of it as a mathematical approach widely used to cut down running time.
Here is an analogy. When you are working through a math workbook and a problem you already solved shows up again, you do not solve it from scratch. You simply copy the answer you wrote down in your notebook. That "answer notebook" is the heart of DP.
For dynamic programming to pay off, the problem must have the following two properties.
| Property | Meaning | Fibonacci example |
|---|---|---|
| Overlapping Subproblems | While computing the answer, the same calculation is repeated over and over | Computing fib(5) ends up computing fib(3) several times |
| Optimal Substructure | The answer to a big problem can be built from the answers to smaller problems | fib(n) = fib(n-1) + fib(n-2) |
"Repeated calculations" describes overlapping subproblems, while optimal substructure means "combining the answers to smaller problems gives the answer to the bigger problem." Both properties are needed to use DP.
Approach
Since it solves a big problem by splitting it into small ones, it is very similar to divide and conquer, as used in merge sort. The difference is whether the small problems overlap when the problem is split.
| Aspect | Divide and conquer | Dynamic programming |
|---|---|---|
| Do the small problems overlap? | No (handled separately, like a left half and a right half) | Yes (the same small problem appears many times) |
| Is storage needed? | No | Answers are stored and reused |
So the key to dynamic programming is to store the computations that keep repeating among the small problems and use them to solve the problem quickly.
Conditions
- Repetition occurs among the small problems
- The same problem always has the same answer
If these two conditions hold, the problem can be solved with dynamic programming. Because the same problem always has the same answer and keeps coming up, we use memoization to work our way up to the big problem.
- Memoization: storing the result of a problem once it has been computed so it never has to be computed again
How It Works
Let's look at the Fibonacci sequence (1, 1, 2, 3, 5, 8, ..., where each number is the sum of the previous two). Solving it with plain recursion repeats the same computations again and again.
fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(4) = fibonacci(3) + fibonacci(2)
fibonacci(3) = fibonacci(2) + fibonacci(1)
When the same computation keeps being reused like this, storing the values in advance with memoization is efficientIf we count how many times each value is computed when finding fib(5) with plain recursion, we get the following.
| Computation | Number of calls |
|---|---|
| fib(5) | 1 |
| fib(4) | 1 |
| fib(3) | 2 |
| fib(2) | 3 |
| fib(1) | 2 |
| Total | 9 |
As n grows, the duplication explodes. Even fib(20) calls the function 13,529 times. Implementing it with memoization so the same work is not repeated makes it efficient.
The steps for solving with DP are as follows.
- Decide the answers to the smallest problems. (fib(1) = 1, fib(2) = 1)
- Solve a few small problems, find the pattern and write a recurrence relation. (fib(i) = fib(i-1) + fib(i-2))
- Fill in a table with answers, starting from the smallest problems. The values you need are already in the table.
| i | Computation | dp[i] |
|---|---|---|
| 1 | Starting value | 1 |
| 2 | Starting value | 1 |
| 3 | dp[2] + dp[1] = 1 + 1 | 2 |
| 4 | dp[3] + dp[2] = 2 + 1 | 3 |
| 5 | dp[4] + dp[3] = 3 + 2 | 5 |
Since you just fill the table one cell at a time, each value is computed exactly once.
The figure below shows which values each value depends on when computing F5. Plain recursion computes F3 and F2 several times, but if you store the answers, there are only five subproblems, F1 to F5, and each one is solved just once.

Image source: Wikimedia Commons (public domain)
Implementation Styles
- Bottom-up: solve the small problems first, step by step (filling a table with loops, also called tabulation)
- Top-down: start with the big problem and, whenever an unsolved small problem comes up, solve it at that point (recursion + memoization)
| Style | Advantages | Things to watch out for |
|---|---|---|
| Bottom-up | No recursion, so no function call overhead and no recursion depth limit | You must decide the order in which to fill the table yourself, so the recurrence is less visible in the code and readability can suffer |
| Top-down | Translates the recurrence almost directly into recursion, so it is easy to read | Deep recursion can hit Python's default recursion limit (about 1000) |
The original source summarizes it as "Bottom-up is easy to solve but less readable, and Top-down is readable but harder to write." The readability comparison matches the table above, and the real difficulty of Top-down lies less in code length and more in recursion depth and call overhead.
When solving a problem with dynamic programming, it is a good idea to start by solving the small cases. As you solve them, you will notice that previously computed, even smaller problems get reused. Once you find this pattern, derive a recurrence relation and apply dynamic programming.
Python Code
# 1. Plain recursion: keeps repeating the same computations
calls = 0
def fib_naive(n):
global calls
calls += 1
if n <= 2:
return 1
return fib_naive(n - 1) + fib_naive(n - 2)
# 2. Top-down: recursion + memoization
def fib_top_down(n, memo=None):
if memo is None:
memo = {}
if n <= 2:
return 1
if n in memo: # If already solved, use the stored answer right away
return memo[n]
memo[n] = fib_top_down(n - 1, memo) + fib_top_down(n - 2, memo)
return memo[n]
# 3. Bottom-up: fill the table starting from small problems
def fib_bottom_up(n):
if n <= 2:
return 1
dp = [0] * (n + 1)
dp[1] = dp[2] = 1
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] # Recurrence relation
return dp[n]
# 4. Bottom-up + space saving: remember only the previous two values
def fib_two_vars(n):
a, b = 1, 1 # fib(1), fib(2)
for _ in range(n - 2):
a, b = b, a + b
return b if n >= 2 else a
print(fib_naive(20), calls) # Output: 6765 13529
print(fib_top_down(20)) # Output: 6765
print(fib_bottom_up(20)) # Output: 6765
print(fib_two_vars(20)) # Output: 6765
print(fib_bottom_up(90)) # Output: 2880067194370816120- This version translates the recurrence directly into recursion. The answer is correct, but fib(20) makes 13,529 calls.
callsis a variable used to count the calls. - The Top-down style. Answers are written into the
memodictionary (a hash map that looks values up by label) and returned immediately if already present. However, if n exceeds 1000, the recursion can get too deep and raise aRecursionError. - The Bottom-up style. It fills the dp table starting from small i, so there is no recursion. It handles large values like fib(90) instantly.
- Since computing dp[i] needs only the previous two values, this version uses just two variables instead of a table.
Time and Space Complexity
For Fibonacci, the amount of work is fixed once n is fixed, so the best, average and worst cases are the same.
| Method | Time (best/average/worst) | Extra space |
|---|---|---|
| Plain recursion | O(2^n) | O(n) (recursion call stack) |
| Top-down (memoization) | O(n) | O(n) (memo + recursion stack) |
| Bottom-up (table) | O(n) | O(n) (dp table) |
| Bottom-up (two variables) | O(n) | O(1) |
- Plain recursion splits into two branches on every call, so it is O(2^n). More precisely it grows by a factor of about 1.618^n, but either way it grows exponentially in n.
- With DP, each of fib(1) through fib(n) is computed only once, so it is O(n).
- If the notation is unfamiliar, see the time complexity article.
Where It Is Used
- Longest Increasing Subsequence (LIS): stores "the length of the longest increasing subsequence ending at the i-th value" in a table.
- Bitmask: represents "which cities have been visited" as a single integer and uses it as a cell index in the DP table. (Traveling salesman problem)
- It is also widely used for problems that "combine the answers to small cases to build the answer to a big case," such as climbing stairs, the knapsack problem and the minimum number of coins.
Summary
| Concept | Plain-language summary |
|---|---|
| Dynamic programming (DP) | Split a big problem into small ones and write solved answers in a notebook to reuse them |
| Overlapping subproblems | A structure where the same small problem appears many times |
| Optimal substructure | A structure where combining the answers to small problems gives the answer to the big problem |
| Memoization | Store an answer once computed and never compute it again |
| Bottom-up | Fill a table in order, starting from small problems (loops) |
| Top-down | Start from the big problem and solve small problems when needed (recursion) |
| Recurrence relation | The rule that builds the next answer from the previous answers |
Reference: Namuwiki - Dynamic Programming
