Dynamic Programming for Beginners: 10 Classic Problems
For software engineers preparing for technical coding interviews or building optimized backend algorithms, Dynamic Programming (DP) is often viewed as one of the most intimidating topics. However, at its core, dynamic programming is simply an optimization technique used to solve complex problems by breaking them down into simpler, overlapping subproblems and storing their results to avoid redundant calculations.
This comprehensive guide demystifies dynamic programming, covering the two foundational approaches—Memoization (Top-Down) and Tabulation (Bottom-Up)—and walks through 10 classic DP problems with clean, production-grade Python implementations.
1. The Two Pillars of Dynamic Programming
A problem can be solved efficiently using dynamic programming if it exhibits two key properties:
- Overlapping Subproblems: The problem can be broken down into subproblems that are reused multiple times in recursive computations (e.g., Fibonacci sequence calculations).
- Optimal Substructure: An optimal solution to the overall problem can be constructed from optimal solutions of its subproblems.
2. Problem 1: Fibonacci Numbers (Memoization vs. Tabulation)
The Fibonacci sequence is the hello world of dynamic programming. A naive recursive approach takes O(2^n) exponential time, whereas DP reduces it to O(n).
# Approach A: Top-Down with Memoization
def fib_memo(n: int, memo: dict = None) -> int:
if memo is None:
memo = {}
if n <= 1:
return n
if n in memo:
return memo[n]
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
# Approach B: Bottom-Up with Tabulation
def fib_tab(n: int) -> int:
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
3. Problem 2: Climbing Stairs
You are climbing a staircase that takes n steps to reach the top. Each time you can either climb 1 or 2 steps. How many distinct ways can you climb to the top?
def climb_stairs(n: int) -> int:
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1], dp[2] = 1, 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
4. Problem 3: Coin Change
Given an array of coin denominations and a total amount of money, compute the fewest number of coins needed to make up that amount.
def coin_change(coins: list, amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if i - coin >= 0:
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
5. Problem 4: 0/1 Knapsack Problem
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value without exceeding capacity.
def knapsack(weights: list, values: list, capacity: int) -> int:
n = len(weights)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])
else:
dp[i][w] = dp[i - 1][w]
return dp[n][capacity]
6. Problem 5: Longest Increasing Subsequence (LIS)
Given an unsorted array of integers, find the length of the longest strictly increasing subsequence.
def length_of_lis(nums: list) -> int:
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
7. Problem 6: Longest Common Subsequence (LCS)
Given two strings text1 and text2, return the length of their longest common subsequence.
def longest_common_subsequence(text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
8. Problem 7: Edit Distance (Levenshtein Distance)
Given two strings word1 and word2, find the minimum number of operations required to convert word1 to word2 (insert, delete, or replace a character).
def min_distance(word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], # Delete
dp[i][j - 1], # Insert
dp[i - 1][j - 1])# Replace
return dp[m][n]
9. Problem 8: House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, but adjacent houses have security systems connected, so you cannot rob two adjacent houses.
def rob(nums: list) -> int:
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[-1]
10. Problem 9: Maximum Subarray (Kadane's Algorithm)
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
def max_sub_array(nums: list) -> int:
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
11. Problem 10: Unique Paths in a Grid
A robot is located at the top-left corner of a m x n grid. It can only move either down or right at any point in time. How many possible unique paths reach the bottom-right corner?
def unique_paths(m: int, n: int) -> int:
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
Conclusion
Mastering dynamic programming is a transformative milestone for any software developer. By identifying overlapping subproblems, establishing recurrence relations, and choosing between memoization and tabulation, you can solve complex optimization problems with optimal time and space complexity.