Optimization · Advanced
Dynamic programming (1D and 2D)
Name the state, write the transition from smaller states, fix the base cases, then fill a table in dependency order so each subproblem is solved once.
On this page
The idea
Dynamic programming applies when a problem breaks into subproblems that overlap (the same state is reached many ways) and the best answer is built from best answers to smaller states. Memoisation caches a recursive solution; tabulation fills an array bottom-up. Both evaluate each state once.
The work is in the state definition. 1D states are usually "best answer for the first i items" or "ending at i". 2D states pair two indices (two strings, a grid cell, an item and a capacity). When a row depends only on the previous row, you can keep two rows, or even two variables, instead of the whole table.
How to recognise it
- "Number of ways", "minimum cost", "maximum value", "is it possible" over sequences or grids.
- A recursive brute force recomputes the same arguments many times.
- Choices at each step (take or skip, step 1 or 2) with an optimal answer built from smaller ones.
- n up to a few thousand for O(n²), or two sequences up to a few thousand each.
When not to use it
- A greedy choice is provably safe: it is simpler and usually faster.
- The state space is too large to store (exponential states); look for a different decomposition or pruning.
- Subproblems do not overlap (plain divide and conquer, like merge sort, gains nothing from caching).
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# 1D: dp[i] = best answer using the first i items
dp = [0] * (n + 1)
dp[0] = base
for i in range(1, n + 1):
dp[i] = best over choices c of (dp[i - step(c)] + gain(c, i))
return dp[n]
# Space-optimised when dp[i] needs only dp[i-1] and dp[i-2]
prev2, prev1 = base0, base1
for i in range(2, n + 1):
prev2, prev1 = prev1, combine(prev1, prev2, i)
# 2D: dp[i][j] over two sequences or a grid, filled row by row
for i in range(rows):
for j in range(cols):
dp[i][j] = combine(dp[i-1][j], dp[i][j-1], dp[i-1][j-1], cell(i, j))- Write the state in one sentence before any code: "dp[i] is the most money from houses 0..i−1".
- Fill in an order where every state you read is already computed.
Complexity
Time O(states × transitions), extra space O(states), often reducible. Climbing stairs has n states and 2 transitions: O(n) time, O(1) space after optimisation. A 2D table over two length-n strings is O(n²) time and O(n²) or O(n) space.
Worked examples
Ways to climb 5 stairs taking 1 or 2 steps
ways(i) = ways(i − 1) + ways(i − 2), with ways(0) = 1 and ways(1) = 1. Filling up: 1, 1, 2, 3, 5, 8. Five stairs can be climbed in 8 ways; the naive recursion would recompute ways(2) several times.
Pitfalls
- A vague state that cannot express the transition.
- Wrong base cases (off by one between "first i items" and "up to index i").
- Reading a table cell before it is filled because of the loop order.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemHow many ways up the stairs?· beginner · O(n)
- ProblemCollect the most without taking neighbours· intermediate · O(n)
- ProblemThe best streak of daily profits· intermediate · O(n)
- ProblemThe cheapest walk down and right· intermediate · O(rows · columns)
- ProblemSet bits for every number up to n· beginner · O(n)
Learn the foundations
Lessons
- ModuleM32 Dynamic Programming· advanced
- ModuleM11 Recursion· intermediate
- Complexity exerciseNaive recursive Fibonacci· Θ(φⁿ) ≈ Θ(1.618ⁿ), within O(2ⁿ)
- Complexity exerciseFilling an n × n table· Θ(n²)
Related patterns
- PatternDepth-first search and backtracking· O(V + E) for graph DFS; O(2ⁿ) subsets, O(n!) permutations
- PatternGreedy choice after sorting· O(n log n)
References
dsa.pattern.dynamic-programming · version 1