Catalog / Dynamic Programming Cheatsheet
Dynamic Programming Cheatsheet
A concise guide to Dynamic Programming concepts, techniques, and common patterns for algorithm design and interview preparation.
Core Concepts
Understanding DP
What is Dynamic Programming? Dynamic Programming (DP) is an algorithmic technique for solving an optimization problem by breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal solution to its subproblems. |
Key Properties:
|
DP vs Divide & Conquer: Unlike Divide & Conquer (e.g., Merge Sort), which divides the problem into independent subproblems, DP is applicable when subproblems are not independent, and subproblems share subsubproblems. |
Approaches
Top-Down (Memoization) |
Start with the main problem and recursively solve subproblems. Store results of subproblems to avoid recomputation. |
Bottom-Up (Tabulation) |
Solve subproblems first and build up to the main problem. Store results in a table (array). |
When to use which approach? |
Memoization can be more intuitive, while tabulation can be more efficient due to reduced function call overhead. |
Steps to Solve DP Problems
|
Common DP Patterns
1D DP
Characteristics: |
Example: Fibonacci Sequence Compute the nth Fibonacci number. Recurrence relation: |
|
2D DP
Characteristics: |
Example: Edit Distance Compute the minimum number of operations (insert, delete, replace) to convert one string to another. Recurrence relation: Based on whether the characters match or not. |
|
Knapsack Pattern
0/1 Knapsack |
Each item can either be included or excluded. |
Unbounded Knapsack |
Each item can be included multiple times. |
Variations |
Subset Sum, Partition Equal Subset Sum, etc. Often involve modifying the knapsack recurrence. |
Optimization Techniques
Space Optimization
Reducing Space Complexity In some DP problems, you only need the previous row or column to compute the current one. In these cases, you can reduce space complexity by using only two rows or columns instead of storing the entire table. |
Example: Fibonacci (Space Optimized)
|
Time Optimization
Avoiding Redundant Calculations Memoization is a key technique to avoid recomputing the same subproblems. Ensure your base cases are correctly defined to prevent infinite recursion. |
Careful Recurrence Design A well-defined recurrence relation can significantly impact the time complexity. Consider alternative formulations that might lead to faster computation. |
Bitmasking
When to Use |
When the problem involves sets or subsets of elements, and the size of the set is relatively small (<= 20). |
Representation |
Represent a set as an integer, where the ith bit is 1 if the ith element is in the set, and 0 otherwise. |
Example |
Traveling Salesman Problem (TSP) variations, Set Cover Problem. |
Practice Problems
Classic Problems
|
Medium Difficulty
|
Hard Difficulty
|
Tips for Interview Prep
|