Skip to main content

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​

  1. Identify recurrence relation
  2. Recursive solution (top-down)
  3. Recursive + Memoization (top-down)
  4. Iterative + Memoization (bottom-up)
  5. Iterative + N variables (bottom-up)
TIP

Fantastic explanation by Abdul Bari on Top Down Approach using Fibonacci example.

Spotting a DP question​

SignalExample 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 laterRobbing 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.

FamilyStateTransition, in wordsExamples
1D lineardp[i] = best answer using the first i itemsTake from i βˆ’ 1 or i βˆ’ 2House Robber, Climbing Stairs, Decode Ways
0/1 knapsackdp[c] = best with capacity cEach item: skip it, or take it oncePartition Equal Subset Sum, Target Sum
Unbounded knapsackdp[c]Each item: skip it, or take it againCoin Change, Coin Change II
2D griddp[r][c]From the cell above and the cell to the leftUnique Paths, 01 Matrix
Two sequencesdp[i][j] = answer for prefixes a[:i], b[:j]Characters match β†’ diagonal; else best of dropping oneLongest Common Subsequence, Edit Distance
Intervaldp[i][j] = answer for s[i..j]Grow from shorter intervals to longerLongest Palindromic Substring, Burst Balloons
State machinedp[i][state]Extra dimension for "holding", "cooling down", "fuel left"Stock with Cooldown, Road Trip
Digit DPdp[position][tight][…]Build the number digit by digitCount 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 directionOn nums = [3], target 6Result
Downwards (0/1)dp[6] reads the old dp[3] = Falseβœ… 3 can't be used twice
Upwardsdp[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​

Context

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.

Hint

Hardest part is identifying the recurrence relation

Recurrence Relation​

4321043210station jstation j+1↑↑↑↑top up i litres ↑drive d = 2: lose 2 litreslitres

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​

tip

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​

Context

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).