NeetCode 150, stage 13: 1-D Dynamic Programming

← Advanced Graphs · All 150 problems · 2-D Dynamic Programming →

Dynamic programming builds the answer to a large problem from the answers to smaller problems. A table keeps each small answer, so the code calculates it only one time. This stage trains four steps that you say in the same order each time: state, base case, transition, answer. Each table here has one index.

Garden notes: the Go syntax for this stage.

Problems on this page

#ProblemLevelPatternTemplate
170. Climbing StairsEasyFibonacci with two variablesA: Two variables
2746. Min Cost Climbing StairsEasyTwo variables, minimum costA: Two variables
3198. House RobberMediumTake or skip, two variablesA: Two variables
4213. House Robber IIMediumTake or skip on a circleA: Two variables
55. Longest Palindromic SubstringMediumExpand from the centreE: Expand from the centre
6647. Palindromic SubstringsMediumExpand from the centreE: Expand from the centre
791. Decode WaysMediumTable over a prefix, countB: Table over a prefix or an amount
8322. Coin ChangeMediumTable over an amount, minimumB: Table over a prefix or an amount
9152. Maximum Product SubarrayMediumBest that ends at i, max and minC: Best that ends at i
10139. Word BreakMediumTable over a prefix, yes or noB: Table over a prefix or an amount
11300. Longest Increasing SubsequenceMediumBest that ends at iC: Best that ends at i
12416. Partition Equal Subset SumMedium0/1 knapsack, subset sum1 knapsack on a boolean row

Templates to memorize

Template A: Two variables

Signal

The answer for step i needs only the answers for i-1 and i-2. The problem says stairs, “one or two steps” or “no two adjacent houses”.

// TEMPLATE A: two variables. Use it when dp[i] reads only dp[i-1] and
// dp[i-2].
// STATE: dp[i] = the answer for the first i items.
// The two variables are a window of two cells that moves along the table.
func countWays(n int) int {
    prev2, prev1 := 1, 1 // BASE CASE: dp[0] and dp[1]
    for i := 2; i <= n; i++ {
        cur := prev1 + prev2      // TRANSITION for "count the ways": add
        prev2, prev1 = prev1, cur // SHIFT the window one cell to the right
    }
    return prev1 // ANSWER: dp[n]
}
 
// The same shape for "take or skip": you cannot take two adjacent items.
func bestNoNeighbours(nums []int) int {
    prev2, prev1 := 0, 0 // BASE CASE: no items, no value
    for _, x := range nums {
        // TRANSITION: SKIP x, or TAKE x on top of dp[i-2]
        cur := max(prev1, prev2+x)
        prev2, prev1 = prev1, cur // SHIFT
    }
    return prev1 // ANSWER
}

The moves are BASE CASE, TRANSITION, then SHIFT. Draw the full table first. Then keep only the two cells that the transition reads. Do the shift after the transition. If you shift first, the transition reads a value that is already new.

Say it

“The answer at i depends only on the two answers before it, so I keep two variables. That is O(n) time and O(1) space.”

Template B: Table over a prefix or an amount

Signal

The problem asks for the fewest pieces, the number of ways, or a yes or no for a full amount or a full string. Each choice removes one piece from the end: a coin, a word, one or two digits.

// TEMPLATE B: a table over an amount. For a string, the index is the prefix
// length.
// STATE: dp[a] = the fewest pieces that make the amount a.
func fewestPieces(pieces []int, target int) int {
    unreachable := target + 1   // more pieces than a real answer can have
    dp := make([]int, target+1) // target+1 cells, so dp[target] exists
    dp[0] = 0                   // BASE CASE: the amount 0 needs no piece
    for a := 1; a <= target; a++ {
        dp[a] = unreachable
        for _, p := range pieces { // TRY each piece as the LAST piece
            if p <= a {
                // TRANSITION: a smaller amount, plus one
                dp[a] = min(dp[a], dp[a-p]+1)
            }
        }
    }
    if dp[target] == unreachable {
        return -1
    }
    return dp[target] // ANSWER
}

The moves are BASE CASE, TRY each last piece, then TRANSITION. The table has target+1 cells, because dp[0] is the empty amount. For a string, dp[i] is the answer for the first i characters. So the last character of that prefix is s[i-1], not s[i]. Most errors in this template are an index that is off by one.

Say it

“dp of a is the best answer for the amount a. I try each coin as the last coin, so the time is O(amount times coins) and the space is O(amount).”

Template C: Best that ends at i

Signal

The problem asks for the longest or the best subsequence or subarray. A state for “the first i items” does not tell you where the last item is. A state for “ends exactly at index i” does.

// TEMPLATE C: "best that ends at i". The best answer can end at each index.
// STATE: dp[i] = the length of the longest rising subsequence that ENDS at
// index i.
func longestRising(nums []int) int {
    dp := make([]int, len(nums))
    best := 0
    for i := 0; i < len(nums); i++ {
        dp[i] = 1                // BASE CASE: nums[i] alone
        for j := 0; j < i; j++ { // LOOK BACK at each earlier end
            // nums[i] can EXTEND the subsequence that ends at j
            if nums[j] < nums[i] {
                dp[i] = max(dp[i], dp[j]+1) // TRANSITION
            }
        }
        // ANSWER: the maximum of all the ends, not dp[n-1]
        best = max(best, dp[i])
    }
    return best
}
 
// For a subarray (no gaps) only i-1 matters, so one variable replaces the
// table.
// nums is not empty.
func bestSubarraySum(nums []int) int {
    // BASE CASE: the subarray that is only nums[0]
    cur, best := nums[0], nums[0]
    for i := 1; i < len(nums); i++ {
        // TRANSITION: START again at i, or EXTEND
        cur = max(nums[i], cur+nums[i])
        best = max(best, cur) // ANSWER
    }
    return best
}

The moves are BASE CASE, LOOK BACK, EXTEND, then take the maximum of all the ends. The answer is not dp[n-1], because the best one can end at each index. For a product, keep the largest and the smallest value that end at i. A negative number changes the smallest value into the largest.

Say it

“dp of i is the best one that ends exactly at index i. Each item extends an earlier one or starts a new one, and the answer is the maximum over all the ends.”

Template D: 0/1 knapsack on a boolean row

Signal

Each item is used at most one time, and the question is whether a subset reaches an exact sum. The problem says partition, “two equal parts” or “subset with sum”.

// TEMPLATE D: 0/1 knapsack on one boolean row. Each item is used at most
// one time.
// STATE: dp[sum] = true if a subset of the items seen so far adds up to
// sum.
func subsetSum(nums []int, target int) bool {
    dp := make([]bool, target+1)
    dp[0] = true             // BASE CASE: the empty subset adds up to 0
    for _, x := range nums { // ITEMS in the outer loop
        // BACKWARDS: dp[sum-x] does not include x yet
        for sum := target; sum >= x; sum-- {
            if dp[sum-x] {
                // TRANSITION: TAKE x on top of a subset that makes sum-x
                dp[sum] = true
            }
        }
    }
    return dp[target] // ANSWER
}

The moves are BASE CASE, ITEMS in the outer loop, then the sums BACKWARDS. The row compresses the table dp[i][sum] for the first i items. If the inner loop goes forwards, dp[sum-x] already includes x. Then the code uses the item two times.

Say it

“This is 0/1 knapsack on the sum. I keep one boolean row and fill it from right to left, so each number is used once. O(n times target) time, O(target) space.”

Template E: Expand from the centre

Signal

The problem says palindrome and substring. A palindrome reads the same from its centre to the left and to the right.

// TEMPLATE E: expand from the centre. A string of length n has 2n-1
// centres.
// It returns the length of the longest palindrome in s.
func longestPalindromeLength(s string) int {
    best := 0
    for centre := 0; centre < len(s); centre++ {
        // ODD: one letter is the centre
        best = max(best, expandFrom(s, centre, centre))
        // EVEN: the centre is a gap
        best = max(best, expandFrom(s, centre, centre+1))
    }
    return best
}
 
// expandFrom moves the two ends out while they hold equal letters.
// It returns the length of the palindrome that it found.
func expandFrom(s string, left, right int) int {
    // CHECK the limits first
    for left >= 0 && right < len(s) && s[left] == s[right] {
        left-- // EXPAND one step on each side
        right++
    }
    return right - left - 1 // the loop stops one step too far on each side
}

The moves are CHOOSE a centre, EXPAND while the two ends are equal, then do the same for the EVEN centre. This template is not a table. A table dp[i][j] for “the substring from i to j is a palindrome” also works, but it uses O(n²) memory. Do not forget the even centre, or the code does not find abba.

Say it

“Every palindrome has a centre, and a string has 2n minus 1 centres. I expand from each one, so the time is O(n squared) and the space is O(1).”

Mistakes in this stage

  • make([]int, n) has no cell for dp[n]. Make n+1 cells when the state is “the first i items”.
  • make fills an int table with 0 and a bool table with false. If 0 is a valid answer, fill the table with a different value for “not reached”.
  • s[i] is a byte. For a digit, calculate int(s[i]-'0') before you do arithmetic.
  • prev2, prev1 = prev1, cur assigns the two variables at the same time. Two separate lines in the wrong order lose a value.

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.

70. Climbing Stairs

LeetCode 70 · Easy

746. Min Cost Climbing Stairs

LeetCode 746 · Easy

198. House Robber

LeetCode 198 · Medium

213. House Robber II

LeetCode 213 · Medium

5. Longest Palindromic Substring

LeetCode 5 · Medium

647. Palindromic Substrings

LeetCode 647 · Medium

91. Decode Ways

LeetCode 91 · Medium

322. Coin Change

LeetCode 322 · Medium

152. Maximum Product Subarray

LeetCode 152 · Medium

139. Word Break

LeetCode 139 · Medium

300. Longest Increasing Subsequence

LeetCode 300 · Medium

416. Partition Equal Subset Sum

LeetCode 416 · Medium


← Advanced Graphs · All 150 problems · 2-D Dynamic Programming →