Algorithms
Dynamic programming, from overlapping subproblems to state spaces
Identify optimal substructure, eliminate redundant calculations with memoization and tabulation, and design state transitions for complex optimization problems.
Plain words. One step at a time. Nothing here assumes you already know the idea.
The idea
Dynamic programming is an algorithm design technique that solves complex optimization and counting problems by breaking them into simpler subproblems, solving each subproblem once, and storing their results to avoid redundant work. It applies specifically to problems exhibiting optimal substructure and overlapping subproblems.
Imagine an accountant calculating total business expenses for every month across several years.
You will need. Basic recursion and call stacks · Time and space complexity using Big-O notation · Familiarity with arrays and hash maps
One pass
Step 1 of 4
Many computations naturally divide into smaller tasks of the exact same form. A standard example is computing the Fibonacci sequence, where each term is the sum of the previous two terms: F(n) = F(n-1) + F(n-2), with base values F(0) = 0 and F(1) = 1. If you write this directly as a naive recursive function, calculating F(5) requires calculating F(4) and F(3). But calculating F(4) also requires F(3) and F(2). Notice that F(3) is computed twice independently, along with all of its sub-branches.
Smallest version
Top-down memoized Fibonacci implementation
def fib_memo(n: int, memo: dict[int, int] | None = None) -> int:
if memo is None:
memo = {}
if n in memo:
return memo[n]
if n <= 0:
return 0
if n == 1:
return 1
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
if __name__ == "__main__":
print(fib_memo(10)) # Output: 55Keep these
- Overlapping subproblems mean the same computational state is reached multiple times across a recursion tree.
- Memoization stores results the first time they are encountered to short-circuit repeated work.
- Optimal substructure guarantees that the best solution to a problem contains within it the best solutions to its subproblems.
Try one
Climbing Stairs
easy