←Back to Tutorials

Dynamic Programming: Master the Patterns

Demystifying DP: Overlapping subproblems, optimal substructure, and the must-know patterns from 1D sequences to 2D grids and Knapsacks.

90 minutes
7Detailed Sections
Senior Level
  • Dynamic Programming (DP) is an optimization over plain recursion. It is used when a problem can be broken down into subproblems, and these subproblems are solved multiple times.
  • Two Requirements for DP:
  1. Overlapping Subproblems: You find yourself solving the same small problem again and again.
  2. Optimal Substructure: The optimal solution to the large problem can be constructed from the optimal solutions of its subproblems.
  • Two Approaches:
  • Top-Down (Memoization): Standard recursion + a cache (usually an array or map) to store results.
  • Bottom-Up (Tabulation): Start from the base cases and fill up a table (typically iterative).

Key Takeaways

1
DP = Recursion + Re-using solutions
2
Memoization: Top-down; cache recursive results
3
Tabulation: Bottom-up; iterative table filling
4
Overlapping subproblems: solves "re-work" in recursion
5
Optimal substructure: builds final answer from sub-answers
6
Senior takeaway: If recursion looks like a tree with repeating nodes, use DP

Visual Diagram


β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Fibonacci: Recursion vs. DP                β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    Plain Recursion: O(2^n)        DP (Memoization): O(n) β”‚
β”‚                                                         β”‚
β”‚          fib(5)                        fib(5)           β”‚
β”‚         /      \                      /      \          β”‚
β”‚     fib(4)    fib(3)              fib(4)    fib(3)      β”‚
β”‚     /    \    /    \              /    \      (memoized)β”‚
β”‚ fib(3) fib(2) fib(2) fib(1)   fib(3) fib(2)             β”‚
β”‚   (repeated) (repeated)                           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Sign in to unlock

Sign In Free