Algorithms · Visualized
Dynamic Programming
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Big-O: The most-asked interview category — 35 classics here.
Dynamic Programming
Remember subproblem answers so no work is ever done twice.
Dynamic programming (DP) applies when a problem has optimal substructure (the best answer is composed of best answers to subproblems) and overlapping subproblems (the same subproblems recur). Instead of recomputing them, DP stores each answer in a table or memo cache keyed by its state. Fibonacci is the smallest example: naive recursion is O(2ⁿ) because f(n−2) is computed twice per level; caching one value per n makes it O(n). Designing a DP means choosing the state — the minimal information that fully describes a subproblem — and the transition — how states combine.
The general recipe
- Define the state precisely: what does dp[i] (or dp[i][j]) mean? Write the sentence out.
- Find the transition: how do smaller states combine into the current one (dp[i] = max(dp[i−1] + a[i], dp[i−1])…)?
- Identify base cases and unreachable states (initialize to −∞/+∞/0 per meaning).
- Choose an evaluation order that guarantees dependencies are ready — top-down memoization or bottom-up tabulation.
- Read the answer from the right cell(s), then consider shaving dimensions (rolling rows) if memory matters.
Vocabulary you'll meet everywhere here
- State
- the parameters that uniquely identify a subproblem — the single most important design decision
- Transition
- the recurrence connecting a state to the states it depends on
- Memoization
- top-down: recursion plus a cache written on first computation of each state
- Tabulation
- bottom-up: fill the table in dependency order with loops, no recursion
- Space optimization
- when dp[i] depends only on dp[i−1], keep two rows instead of n
Where this family shows up
- Knapsack family, coin change, subset/partition sums
- Sequence alignment: LCS, edit distance, palindromic substrings
- Grid path counting, stock problems with states, bitmask DP over subsets (TSP)
Common pitfalls
- A state that is missing information (e.g. forgetting “remaining capacity”) makes correct transitions impossible
- Wrong base cases poison every cell derived from them — verify the first row/column by hand
- Iterating in an order that reads cells not yet computed (silent wrong answers)
- Mixing top-down and bottom-up conventions: memo keys must capture the full state
def fibonacci(n):
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return bRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.