awelgorithms

// learn

Dynamic programming, from memoization to knapsack

Dynamic programming solves a problem by solving smaller versions of it once each and reusing the answers. It applies when a recursive solution keeps asking the same questions: fib(5) needs fib(4) and fib(3), fib(4) needs fib(3) again, and the repeats grow exponentially.

Updated

Every DP solution comes down to the same three choices: the state (what one subproblem is, like "the best answer using the first i houses"), the recurrence (how a state is built from smaller ones), and the base cases. Get those right and the code is a few lines, written either top-down with a cache or bottom-up with a table.

When to use it

The template

from functools import cache

def rob(houses):                    # House Robber
    @cache                          # memoization: each i is solved once
    def best(i):                    # state: best total from house i onwards
        if i >= len(houses):
            return 0                # base case: no houses left
        take = houses[i] + best(i + 2)
        skip = best(i + 1)
        return max(take, skip)      # recurrence: take this house or skip it
    return best(0)

The variants you will meet

Memoization and tabulation

Top-down memoization adds a cache to the recursive solution; bottom-up tabulation fills a table from the base cases up. Same recurrence, same complexity, and tabulation lets you keep only the last row or two.

1D DP

The state is one index: climbing stairs, house robber, maximum subarray (Kadane's algorithm is a one-variable DP) and longest increasing subsequence.

2D DP

Two indexes, usually a position in each of two strings or a cell in a grid: longest common subsequence, edit distance, unique paths.

Knapsack

Choose items under a capacity. In 0/1 knapsack each item is used once; in unbounded knapsack (coin change) items repeat. Subset sum and partition equal subset sum are knapsack with true/false values.

Intervals, trees, graphs and bitmasks

The state can be a range [i, j] split into two halves, a tree node combining its children, a node in a DAG processed in topological order, or a set of visited items stored as a bitmask.

Time and space complexity

Time is the number of states times the work per state: House Robber has n states with O(1) work, so O(n); edit distance has m·n states, so O(m·n). Space is the number of states you store, often reducible to one or two rows with a rolling array.

check which skills you have 10 minutes, free, no account.

All 17 lessons, in order

Common questions

What is the difference between memoization and tabulation?

Memoization is top-down: write the recursion and cache each result. Tabulation is bottom-up: fill a table in an order where every state's inputs are ready. Both compute each state once; memoization skips states it never needs, tabulation avoids recursion depth limits and makes space savings easy.

How do I know a problem is dynamic programming?

Look for a question about the number of ways, the best cost, or whether something is possible, where each decision leaves a smaller copy of the same problem. If your recursive solution calls itself with the same arguments more than once, a cache turns it into DP.

How do I find the DP state?

Ask what you need to know to finish the problem from this point on, and nothing more. For House Robber that is just the index of the next house. If two different paths reach the same situation and the rest of the problem is identical, that situation is your state.

Is dynamic programming the same as recursion?

No. Recursion is a way of writing code; dynamic programming is the idea of solving each subproblem once. A recursive solution without a cache can be exponential. With a cache, or rewritten as a loop over a table, it becomes DP.

Other guides