NeetCode 150, stage 14: 2-D Dynamic Programming

← 1-D Dynamic Programming · All 150 problems · Greedy →

These problems need a table with two indexes. The indexes can be two cells of a grid, two prefixes of two strings, an item and an amount, or the ends of an interval. Say the same four steps as in the 1-D stage: state, base case, transition, answer. Draw the table on paper before you write the loops, because the loop order comes from the cells that each cell reads.

Garden notes: the Go syntax for this stage.

Problems on this page

#ProblemLevelPatternTemplate
162. Unique PathsMediumGrid paths, one rowA: Grid paths
21143. Longest Common SubsequenceMediumTwo strings tableB: Two strings table
3309. Best Time to Buy and Sell Stock with CooldownMediumState machine by dayD: State machine by day
4518. Coin Change IIMediumUnbounded knapsack, countC: Knapsack count on one row
5494. Target SumMedium0/1 knapsack count, subset sumC: Knapsack count on one row
697. Interleaving StringMediumTwo strings table, yes or noB: Two strings table
7329. Longest Increasing Path in a MatrixHardDFS with memo on a gridF: DFS with memo on a grid
8115. Distinct SubsequencesHardTwo strings table, countB: Two strings table
972. Edit DistanceMediumTwo strings table, minimumB: Two strings table
10312. Burst BalloonsHardInterval DP, last to burstE: Interval DP
1110. Regular Expression MatchingHardTwo strings table, pattern matchB: Two strings table

Templates to memorize

Template A: Grid paths

Signal

A robot or a path moves in a grid, only right or down. The problem asks for the number of paths or for the best cost of a path.

// TEMPLATE A: grid paths. The moves are only right or down.
// STATE: dp[r][c] = the number of paths from the top-left cell to the cell
// (r, c).
func gridPaths(rows, cols int) int {
    dp := make([][]int, rows)
    for r := 0; r < rows; r++ {
        dp[r] = make([]int, cols) // each row needs its own make
        // BASE CASE: one path down the first column
        dp[r][0] = 1
    }
    for c := 0; c < cols; c++ {
        dp[0][c] = 1 // BASE CASE: one path along the first row
    }
    for r := 1; r < rows; r++ {
        for c := 1; c < cols; c++ {
            // TRANSITION: from ABOVE plus from the LEFT
            dp[r][c] = dp[r-1][c] + dp[r][c-1]
        }
    }
    return dp[rows-1][cols-1] // ANSWER: the bottom-right cell
}

The moves are BASE CASE for the first row and the first column, then TRANSITION from the cell above and the cell on the left. Each cell reads only the row above and its own row. So one row is sufficient, and the standard answer keeps one row. Fill the base cells before the main loops, or the index r-1 goes out of range.

Say it

“A cell is reached from above or from the left, so its count is the sum of those two cells. That is O(m times n) time, and I can keep one row for O(n) space.”

Template B: Two strings table

Signal

The input is two strings, and the problem compares them. The problem says common subsequence, edit distance, interleave, or a pattern that matches a text.

// TEMPLATE B: a table for two strings, with an extra row and an extra
// column.
// STATE: dp[i][j] = the answer for the first i bytes of a and the first j
// bytes of b.
// Here the answer is the length of the longest common subsequence.
func commonLength(a, b string) int {
    // EXTRA ROW: row 0 is the empty prefix of a
    dp := make([][]int, len(a)+1)
    for i := range dp {
        // EXTRA COLUMN. BASE CASE: row 0 and column 0 stay 0
        dp[i] = make([]int, len(b)+1)
    }
    for i := 1; i <= len(a); i++ {
        for j := 1; j <= len(b); j++ {
            if a[i-1] == b[j-1] { // the LAST bytes of the two prefixes
                // MATCH: the diagonal cell, plus one
                dp[i][j] = dp[i-1][j-1] + 1
            } else {
                // NO MATCH: drop one last byte
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
            }
        }
    }
    return dp[len(a)][len(b)] // ANSWER: the two full strings
}

The moves are EXTRA ROW AND COLUMN, BASE CASE, then MATCH or NO MATCH. The cell dp[i][j] is the answer for the first i bytes of a and the first j bytes of b. So the bytes to compare are a[i-1] and b[j-1]. Row 0 and column 0 are the empty prefixes, and each problem gives them a different base value.

Say it

“dp i j is the answer for the first i characters of one string and the first j of the other. Each cell reads the diagonal, the cell above and the cell on the left, so it is O(n times m).”

Template C: Knapsack count on one row

Signal

The problem asks for the number of ways to reach an amount or a sum. A different order of the same items is not a new way.

// TEMPLATE C: count the ways to reach a sum, on one row.
// STATE: dp[s] = the number of ways to make the sum s with the items seen
// so far.
// UNBOUNDED: each item can be used many times, so the inner loop goes
// FORWARDS.
func countUnbounded(items []int, target int) int {
    dp := make([]int, target+1)
    dp[0] = 1 // BASE CASE: one way to make 0, with no items
    // ITEMS in the outer loop: an order is not a new way
    for _, x := range items {
        for s := x; s <= target; s++ {
            dp[s] += dp[s-x] // ADD: dp[s-x] can already include x
        }
    }
    return dp[target] // ANSWER
}
 
// 0/1: each item is used at most one time, so the inner loop goes
// BACKWARDS.
func countZeroOne(items []int, target int) int {
    dp := make([]int, target+1)
    dp[0] = 1 // BASE CASE
    for _, x := range items {
        for s := target; s >= x; s-- {
            dp[s] += dp[s-x] // ADD: dp[s-x] is still the value without x
        }
    }
    return dp[target] // ANSWER
}

The moves are BASE CASE dp[0] = 1, ITEMS in the outer loop, then ADD. The direction of the inner loop is the only difference between the two functions. A forward loop lets an item be used again. A backward loop uses each item one time. If the amount is in the outer loop, the code counts each order as a different way.

Say it

“dp of s is the number of ways to make s. I loop over the items first, so I count combinations and not orders. Forwards means unlimited use, backwards means each item once.”

Template D: State machine by day

Signal

Each day you are in one of a few states, for example “has a share” or “has no share”. A rule such as a cooldown or a fee limits the moves between the states.

// TEMPLATE D: a state machine by day. Buy and sell one share as many times
// as you want.
// STATE: hold = the best profit at the end of the day when you have a
// share.
// cash = the best profit at the end of the day when you have no share.
func bestProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    // BASE CASE: on day 0 you buy, or you do nothing
    hold, cash := -prices[0], 0
    for day := 1; day < len(prices); day++ {
        p := prices[day]
        newHold := max(hold, cash-p) // TRANSITION: keep the share, or BUY
        newCash := max(cash, hold+p) // TRANSITION: keep the cash, or SELL
        // UPDATE all the states together, from the old values
        hold, cash = newHold, newCash
    }
    return cash // ANSWER: a share that you still have gives no profit
}

The moves are STATES, one TRANSITION for each state, then UPDATE. The table is dp[day][state], and one variable for each state compresses it. Calculate all the new values from the old values before you assign them. If you assign one state too early, the next line reads the value of today, not of yesterday.

Say it

“I keep the best profit for each state at the end of each day. Each state has one transition from yesterday, so it is O(n) time and O(1) space.”

Template E: Interval DP

Signal

The value of an operation depends on the neighbours, and each operation changes the neighbours. The problem says burst, merge, cut or multiply in a range.

// TEMPLATE E: interval DP. score(lo, k, hi) is the value of the LAST
// operation, at k.
// STATE: dp[lo][hi] = the best total for the items strictly between lo and
// hi.
func bestInterval(n int, score func(lo, k, hi int) int) int {
    if n < 2 {
        return 0
    }
    dp := make([][]int, n)
    for i := range dp {
        // BASE CASE: an interval with no item inside is 0
        dp[i] = make([]int, n)
    }
    for length := 2; length < n; length++ { // SHORT intervals first
        for lo := 0; lo+length < n; lo++ {
            hi := lo + length
            // SPLIT: k is the last operation in (lo, hi)
            for k := lo + 1; k < hi; k++ {
                total := dp[lo][k] + score(lo, k, hi) + dp[k][hi]
                dp[lo][hi] = max(dp[lo][hi], total) // TRANSITION
            }
        }
    }
    return dp[0][n-1] // ANSWER: the full interval
}

The moves are LAST operation, SPLIT at k, then SHORT intervals first. The last operation divides the interval into two parts that do not touch each other. The first operation does not do that, because it makes two far items into neighbours. The loop on the length must be the outer loop, so the two shorter intervals are ready.

Say it

“I choose which item is handled last in the interval. That splits it into two independent intervals. There are n squared intervals and n split points, so it is O(n cubed).”

Template F: DFS with memo on a grid

Signal

The path in the grid moves in four directions, so no row order is correct for a table. Each move follows a strict rule, for example to a larger value, so a path cannot return to a cell.

// TEMPLATE F: DFS with a memo on a grid. A move goes to a strictly smaller
// neighbour.
// STATE: memo[r][c] = the length of the longest path that STARTS at (r, c).
// 0 = not known.
func longestDownhill(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    memo := make([][]int, rows)
    for r := range memo {
        memo[r] = make([]int, cols)
    }
    dirs := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
    // declare first, so the closure can call itself
    var dfs func(r, c int) int
    dfs = func(r, c int) int {
        if memo[r][c] != 0 { // CHECK THE MEMO
            return memo[r][c]
        }
        best := 1                // BASE CASE: the cell alone
        for _, d := range dirs { // EXPLORE the four neighbours
            nr, nc := r+d[0], c+d[1]
            if nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] < grid[r][c] {
                best = max(best, 1+dfs(nr, nc)) // TRANSITION
            }
        }
        memo[r][c] = best // STORE
        return best
    }
    best := 0
    for r := 0; r < rows; r++ {
        for c := 0; c < cols; c++ {
            best = max(best, dfs(r, c)) // ANSWER: the best start cell
        }
    }
    return best
}

The moves are CHECK THE MEMO, EXPLORE the four neighbours, then STORE. The strict rule makes the recursion stop, and no visited set is necessary. The memo makes each cell cost one calculation, so the time is O(rows × cols). Without the memo the time is exponential.

Say it

“The longest path from a cell is one plus the best of its larger neighbours. I cache that per cell, so each cell is computed once: O(m times n) time and space.”

Mistakes in this stage

  • make([][]int, n) makes n rows that are nil. Make each row in a loop before you write to it.
  • Each row needs its own make. Two rows that share one slice change together.
  • With the extra row and column, the bytes are a[i-1] and b[j-1]. The index a[i] is off by one, and it panics on the last row.
  • A closure that calls itself needs two lines. Write var dfs func(r, c int) int first, then dfs = func(...).

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

62. Unique Paths

LeetCode 62 · Medium

1143. Longest Common Subsequence

LeetCode 1143 · Medium

309. Best Time to Buy and Sell Stock with Cooldown

LeetCode 309 · Medium

518. Coin Change II

LeetCode 518 · Medium

494. Target Sum

LeetCode 494 · Medium

97. Interleaving String

LeetCode 97 · Medium

329. Longest Increasing Path in a Matrix

LeetCode 329 · Hard

115. Distinct Subsequences

LeetCode 115 · Hard

72. Edit Distance

LeetCode 72 · Medium

312. Burst Balloons

LeetCode 312 · Hard

10. Regular Expression Matching

LeetCode 10 · Hard


← 1-D Dynamic Programming · All 150 problems · Greedy →