Dynamic Programming
Dynamic programming has been my nemesis for awhile now and it is about time I tackle dynamic programming using the same approach for dynamic programming.
What is Dynamic Programmingβ
Find out all possible solutions, then pick out best solution.
Recursive in nature.
Principle of Optimality: A problem can be solved by taking a sequence of decisions to get the optimal solution.
Top Down Approachβ
- Identify recurrence relation
- Recursive solution (top-down)
- Recursive + Memoization (top-down)
- Iterative + Memoization (bottom-up)
- Iterative + N variables (bottom-up)
Fantastic explanation by Abdul Bari on Top Down Approach using Fibonacci example.
Spotting a DP questionβ
| Signal | Example wording |
|---|---|
| Optimise over choices | "minimum cost", "maximum profit", "longest" |
| Count the ways | "how many distinct ways", "number of paths" |
| Is it possible | "can you reach", "can you partition" |
| Choices now limit choices later | Robbing a house blocks its neighbour; fuel now limits the next leg |
If the same subproblem gets solved more than once in the recursion tree, memoise it. In Python, @functools.cache on the recursive function turns step 2 into step 3 of the approach above.
Common Approaches to DP Questionsβ
Most interview DP questions belong to a handful of families. Name the family and the state falls out.
| Family | State | Transition, in words | Examples |
|---|---|---|---|
| 1D linear | dp[i] = best answer using the first i items | Take from i β 1 or i β 2 | House Robber, Climbing Stairs, Decode Ways |
| 0/1 knapsack | dp[c] = best with capacity c | Each item: skip it, or take it once | Partition Equal Subset Sum, Target Sum |
| Unbounded knapsack | dp[c] | Each item: skip it, or take it again | Coin Change, Coin Change II |
| 2D grid | dp[r][c] | From the cell above and the cell to the left | Unique Paths, 01 Matrix |
| Two sequences | dp[i][j] = answer for prefixes a[:i], b[:j] | Characters match β diagonal; else best of dropping one | Longest Common Subsequence, Edit Distance |
| Interval | dp[i][j] = answer for s[i..j] | Grow from shorter intervals to longer | Longest Palindromic Substring, Burst Balloons |
| State machine | dp[i][state] | Extra dimension for "holding", "cooling down", "fuel left" | Stock with Cooldown, Road Trip |
| Digit DP | dp[position][tight][β¦] | Build the number digit by digit | Count Digits 0, 2 and 4 |
Knapsack: the loop direction is the whole differenceβ
With a 1D array, iterating capacity downwards uses each item at most once; upwards lets it be reused.
def canPartition(nums): # 0/1: each number used once
total = sum(nums)
if total % 2:
return False
dp = [True] + [False] * (total // 2) # dp[c]: can some subset sum to c?
for n in nums:
for c in range(total // 2, n - 1, -1): # downwards
dp[c] = dp[c] or dp[c - n]
return dp[-1]
def coinChange(coins, amount): # unbounded: each coin reused
dp = [0] + [float("inf")] * amount # dp[c]: fewest coins to make c
for coin in coins:
for c in range(coin, amount + 1): # upwards
dp[c] = min(dp[c], dp[c - coin] + 1)
return dp[amount] if dp[amount] != float("inf") else -1
| Loop direction | On nums = [3], target 6 | Result |
|---|---|---|
| Downwards (0/1) | dp[6] reads the old dp[3] = False | β 3 can't be used twice |
| Upwards | dp[3] becomes True, then dp[6] reads it | β Counts 3 + 3 for a single 3 |
Two sequencesβ
def longestCommonSubsequence(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] # row/col 0 = empty prefix
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1 # extend the diagonal
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) # drop a char from one side
return dp[-1][-1]
Edit Distance is the same table with 1 + min(insert, delete, replace) in the else branch.
Example Solutionsβ
Road Tripβ
Below is a question I had encountered during one of the technical assessment that tripped me.
You are going on a road trip. You are going to get in your trusty car and drive to Panglossia, where you will spend a nice vacation by the beach. Your car holds C litre of petrol and gets m km per litre. You are handed a list of the n petrol stations are on the road and the price they sell petrol.
Let distance[i] be the distance of the i-th gas station from Start, let cost[i] be the cost of petrol per litre at the i-th station. Furthermore, you can assume that for any two stations i and j, the distance |distance[i] - distance[j]| between them is divisible by m. You start out with an empty tank at station 1. Your final destination is station n.
Hardest part is identifying the recurrence relation
Recurrence Relationβ
Figure DP-1: The state is (station, litres in tank). Each β tops up one litre at station j; red arrows are the drive to station j+1, which costs d litres whatever you arrive with.
for each possible i: C(station j, k) = C(station j+1, k - d + i) + cost(station j) * i
C(station j, k): minimum cost to reach destination from station j, with k litre in tank
k: k litre of fuel
d: distance from station j to station j+1
i: amount of fuel topped up
Approachβ
You can observe that if you have already solved the problem for all j' > j, then it is not hard to compute C(station j, k).
If you start with k litres and it is d km from the next station, then for all i, lookup the already computed C(station j+1, k - d + i), which tells you the minimum cost for arriving at station j+1 with k - d + i litres of petrol. Add this cost per litre at station j times i, and choose the i that is the cheapest.
Work in reverse until you get to the first station, and you will eventually find the cheapest way to reach destination.
Solutionβ
def minimumCost(distance, n, C, cost, m):
dp = [[0 for i in range(C)] for j in range(n)]
for j in range(n - 2, -1, -1): # Traverse all stations in reverse
for k in range(C): # How much fuel in tank starting from station j
d_next = (distance[j+1] - distance[j]) // m
min_ = float('inf')
for i in range(C-k): # How much fuel topped up
if k + i >= d_next:
min_ = min(min_, dp[j+1][k - d_next + i] + cost[j] * i)
dp[j][k] = min_
print(dp)
return (dp[0][0])
C = 10 # Capacity of petrol; starts with 0
n = 3
cost = [10,1,1]
d = [0, 20, 100] # distance of ith station from start
m = 10 # km/litre
minimumCost(d, n, C, cost, m)
House Robberβ
Recurrence Relationβ
Robber has 2 options: (Knap-sack problems)
- Rob current house
- Don't rob current house
Robber has to maximize profits using these 2 scenarios:
- Rob current house + loot from houses before the previous
- Loot from the previous house and those before that
rob(i) = max(rob(i - 2) + i, rob(i - 1))
Solutionβ
Let rob1 = i - 2 and rob2 = i - 1.
# [rob1, rob2, i, i+1, ...]
def rob(nums):
rob1 = rob2 = 0
for i in nums:
temp = max(rob1 + i, rob2)
# Shift rob variable forward
rob1 = rob2
rob2 = temp
return rob2
Space Complexity: O(1) as there are always only 2 variables (rob1, rob2) used.
Time Complexity: O(n) as there is only one loop through the nums array.
01 Matrixβ
Excellent leetcode explanation by hiepit.
Solution 1: DP with Top-Down and Bottom-Upβ
def updateMatrix(self, mat):
r, c = len(mat), len(mat[0])
# Top-Down Approach
for i in range(r):
for j in range(c):
if mat[i][j] > 0: # cells that needs to be updated
left = mat[i][j-1] if j > 0 else math.inf
top = mat[i-1][j] if i > 0 else math.inf
mat[i][j] = 1 + min(left, top)
# Bottom-Up Approach
for i in range(r-1, -1, -1):
for j in range(c-1, -1, -1):
if mat[i][j] > 0:
right = mat[i][j+1] if j < c-1 else math.inf
bot = mat[i+1][j] if i < r-1 else math.inf
mat[i][j] = min(mat[i][j], 1 + right, 1 + bot)
return mat
Time Complexity: O(M * N) due to the double for loops to run through the matrix.
Space Complexity: O(1) as no additional data structures were used.
Solution 2: BFS starting from zeroesβ
def updateMatrix(self, mat):
DIR = [(0,1), (1,0), (0,-1), (-1,0)]
queue = []
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 0:
queue.append((i, j))
else:
mat[i][j] = -1 # marked as not processed
while queue:
r, c = queue.pop(0)
# Check all four directions
for x, y in DIR:
nr, nc = r + x, c + y
# Check out of bounds and already processed
if nr < 0 or nr >= len(mat) or nc < 0 or nc >= len(mat[0]) or mat[nr][nc] != -1:
continue
mat[nr][nc] = 1 + mat[r][c]
queue.append((nr, nc))
return mat
Time Complexity: O(M * N) due to the double for loops to run through the matrix.
Space Complexity: O(M * N) due to the queue used.
Count Digits 0, 2 and 4β
Given n, count how many times the digits 0, 2 and 4 appear across all integers from 1 to n.
For n = 100 the answer is 51.
Brute force is O(n log n) β loop to n, count digits. That dies for n = 10^9.
The trick is to count one digit at one place value at a time, in O(log n).
Recurrence Relationβ
Split n around the place value p (1, 10, 100, ...) you are counting at:
high = n // (p * 10) # digits above p
cur = (n // p) % 10 # the digit at p
low = n % p # digits below p
# for d > 0
cur > d -> (high + 1) * p
cur == d -> high * p + low + 1
cur < d -> high * p
Reading of cur > d: every full block of high + 1 prefixes contributes p numbers whose
digit at p is d. When cur == d the last block is partial, so only low + 1 of it counts.
d = 0 is the special case: a prefix of 0 means leading zeros, which are not real digits.
So high becomes high - 1.
Solutionβ
def count_digit(n, d):
total, p = 0, 1
while p <= n:
high, cur, low = n // (p * 10), (n // p) % 10, n % p
if d == 0:
# high - 1 skips the leading-zero prefix
total += (high - 1) * p + low + 1 if cur == 0 else high * p
elif cur > d:
total += (high + 1) * p
elif cur == d:
total += high * p + low + 1
else:
total += high * p
p *= 10
return total
def count_024(n):
return sum(count_digit(n, d) for d in (0, 2, 4))
Sanity check against brute force:
def brute(n, d):
return sum(str(i).count(str(d)) for i in range(1, n + 1))
for n in range(1, 3000):
for d in range(10):
assert count_digit(n, d) == brute(n, d), (n, d)
Time Complexity: O(log n) β one iteration per digit of n, times 3 digits.
Space Complexity: O(1).