memory

Dynamic Programming
Curriculum

Master optimization through overlapping subproblems, optimal substructure, and systematic state-space exploration.

What This Category Is Really About

content_copyOverlapping Subproblems

Same subproblems solved repeatedly. Cache results to avoid recomputation. Memoization (top-down) or tabulation (bottom-up).

architectureOptimal Substructure

Optimal solution built from optimal solutions to subproblems. Local optimality leads to global optimality.

grid_onState Definition

Define state that captures subproblem. State transitions define recurrence relation. DP table stores computed states.

functionsRecurrence Relations

Express solution in terms of smaller subproblems. Base cases terminate recursion. Transitions define computation order.

Mental Model & Invariants

DP is recursion with memory—avoid recomputing by caching.

"Break problem into subproblems. If subproblems overlap, cache results. If optimal substructure exists, combine cached solutions optimally."

The Core Invariant
Each subproblem is solved exactly once. Results are stored and reused. State transitions maintain correctness through optimal substructure.

Break this, and you either recompute or get wrong answers.

memory

Memoization

Top-down: write recursive solution, add cache. Compute on demand. Natural for thinking recursively.

table_chart

Tabulation

Bottom-up: fill table iteratively. Compute in dependency order. Often more space-efficient.

compress

Space Optimization

Often only need previous row/column. Reduce O(n²) space to O(n). Sliding window over DP table.

psychology

Think in States

Define state that captures subproblem. Identify state transitions. Write recurrence relation. Choose memoization or tabulation.

When to Think "Dynamic Programming"

sensorsStrong Signals

draw

Optimization problem (min/max/count)

draw

Overlapping subproblems visible

draw

Choices at each step

draw

Optimal substructure present

draw

Exponential brute force

draw

"How many ways" questions

ruleProblem Patterns

memory

Sequence/string problems

memory

Grid path problems

memory

Knapsack variants

memory

Partition problems

Core Patterns You Must Master

stairs

Linear DP

1D array. Each state depends on previous states. Climbing stairs, house robber, decode ways.

// Invariant
dp[i] computed from dp[i-1], dp[i-2], etc.
1DSequentialFibonacci
grid_on

2D Grid DP

2D table. State depends on adjacent cells. Unique paths, minimum path sum, edit distance.

// Invariant
dp[i][j] from dp[i-1][j], dp[i][j-1], dp[i-1][j-1].
2DGridPaths
shopping_bag

Knapsack

0/1 knapsack, unbounded knapsack, subset sum. Include/exclude decisions.

// Invariant
dp[i][w] = max(include item i, exclude item i).
0/1UnboundedSubset
text_fields

String DP

Longest common subsequence, palindrome problems, edit distance. Character matching.

// Invariant
Match characters or skip. Build from smaller strings.
LCSPalindromeEdit
account_tree

Tree DP

DP on tree structures. House robber III, binary tree cameras. Subtree solutions.

// Invariant
Combine solutions from left and right subtrees.
TreeSubtreeRecursive
compress

State Compression

Bitmask DP for small state spaces. Traveling salesman, subset enumeration.

// Invariant
State represented as bitmask. Transitions flip bits.
BitmaskTSPSubset

How to Learn This Category

1

Master Fibonacci Pattern

Start with climbing stairs. Understand how dp[i] depends on previous states. Practice writing recurrence relations.

2

Learn Memoization First

Write recursive solution. Add cache (hashmap/array). Understand top-down approach before bottom-up.

3

Practice State Definition

What does dp[i] or dp[i][j] represent? Clear state definition is critical. Write it down explicitly.

4

Draw the DP Table

Visualize how table fills. Understand dependency order. See patterns in how values propagate.

5

Convert to Tabulation

Take memoized solution, convert to bottom-up. Understand iteration order. Practice both approaches.

6

Optimize Space

Identify if only previous row/column needed. Reduce space from O(n²) to O(n). Use rolling arrays.

Canonical Problem List

Common Mistakes

error_outline

Unclear State Definition

Failure Mode

Don't know what dp[i] represents. Leads to wrong recurrence relation.

Mastery Fix

Write explicit state definition before coding. What does each dimension represent?

error_outline

Wrong Base Cases

Failure Mode

Incorrect initialization. DP table starts with wrong values.

Mastery Fix

Identify base cases from problem. Initialize dp table correctly before filling.

error_outline

Incorrect Iteration Order

Failure Mode

Computing dp[i] before dependencies available. Results in wrong values.

Mastery Fix

Understand dependency graph. Iterate in order that ensures dependencies computed first.

error_outline

Not Considering All Transitions

Failure Mode

Missing state transitions. Optimal solution not explored.

Mastery Fix

For each state, consider all possible previous states. Enumerate all transitions.

error_outline

Forgetting to Cache in Memoization

Failure Mode

Recomputing same subproblems. No speedup over brute force.

Mastery Fix

Check cache before computing. Store result after computing. Return cached value if exists.

Interview Guidance

Interview Protocol

What they test

  • State definition clarity
  • Recurrence relation correctness
  • Base case identification
  • Memoization vs tabulation choice

Strategy

Start with brute force recursive solution. Identify overlapping subproblems. Define state clearly. Write recurrence relation. Add memoization or build table bottom-up.

The Verbal Template

State

"dp[i] represents [what]. dp[i][j] represents [what for dimensions i and j]."

Recurrence

"dp[i] = [function of previous states]. This captures [why this transition is correct]."

Base Case

"When [condition], dp value is [base value]. This handles [edge case]."

Complexity

"Time: O([states] × [transitions per state]). Space: O([DP table size])."

When You've Mastered It

done_all

Define state clearly and quickly

done_all

Write recurrence relations correctly

done_all

Identify overlapping subproblems

done_all

Choose memoization vs tabulation

done_all

Optimize space when possible

done_all

Recognize DP patterns instantly

What This Unlocks Next

functions

Advanced DP Patterns

Digit DP, probability DP, DP on trees, bitmask DP. Complex state spaces and transitions.

speed

DP Optimizations

Convex hull trick, divide and conquer optimization, monotonic queue optimization. Reduce complexity.

casino

Game Theory

Minimax, alpha-beta pruning, Nim games. DP for optimal strategies in adversarial settings.

analytics

Computational Geometry

Closest pair, convex hull, line sweep. DP for geometric optimization problems.