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.
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:
Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
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.
Idea. The last move to step n is 1 step or 2 steps. So the number of ways to reach step n is the sum of the ways for the two steps before it.
Complexity. Time O(n), space O(1).
Go lesson. Go assigns a tuple in one statement. prev2, prev1 = prev1, cur reads the two old values before it writes.
Step 3: the Go solution
// climbStairs solves LC 70. Time O(n), space O(1).// STATE: dp[i] = the number of ways to reach step i.// BASE CASE: dp[0] = 1 (you are on the floor) and dp[1] = 1.// TRANSITION: dp[i] = dp[i-1] + dp[i-2], because the last move is 1// step or// 2 steps.// ANSWER: dp[n].// The two variables compress the table dp[0..n]: a cell reads only// the two// cells before it.func climbStairs(n int) int { // BASE CASE: prev2 is dp[0], prev1 is dp[1] prev2, prev1 := 1, 1 for i := 2; i <= n; i++ { // TRANSITION: dp[i] = dp[i-1] + dp[i-2] cur := prev1 + prev2 // SHIFT: the window moves one step up prev2, prev1 = prev1, cur } return prev1 // ANSWER: after the loop, prev1 is dp[n]}
Idea. You reach step i from step i-1 or from step i-2, and you pay the cost of the step that you leave. Keep the cheaper of the two.
Complexity. Time O(n), space O(1).
Go lesson. The built-in min and max work on two or more values of one ordered type. They are in the language from Go 1.21.
Step 3: the Go solution
// minCostClimbingStairs solves LC 746. Time O(n), space O(1).// STATE: dp[i] = the minimum cost to stand on step i. The top is// step n,// after the last step.// BASE CASE: dp[0] = 0 and dp[1] = 0, because you can start on step// 0 or on// step 1.// TRANSITION: dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] +// cost[i-2]). You// pay when you leave.// ANSWER: dp[n].// The two variables compress the table dp[0..n]: a cell reads only// the two// cells before it.func minCostClimbingStairs(cost []int) int { // BASE CASE: prev2 is dp[0], prev1 is dp[1] prev2, prev1 := 0, 0 // <= because the top is the index len(cost) for i := 2; i <= len(cost); i++ { // TRANSITION: the cheaper way to step i cur := min(prev1+cost[i-1], prev2+cost[i-2]) prev2, prev1 = prev1, cur // SHIFT } return prev1 // ANSWER: dp[n]}
Idea. At each house you make one decision. Skip it and keep the best of the houses before it, or rob it and add the best that ends two houses back.
Complexity. Time O(n), space O(1).
Go lesson.for _, x := range nums gives the value and drops the index. The loop does not need the index, because the two variables hold the history.
Step 3: the Go solution
// rob solves LC 198. Time O(n), space O(1).// STATE: dp[i] = the most money from the first i houses.// BASE CASE: dp[0] = 0, because no houses give no money.// TRANSITION: dp[i] = max(dp[i-1], dp[i-2] + nums[i-1]). SKIP house// i, or// TAKE it.// ANSWER: dp[n].// The two variables compress the table dp[0..n]: a cell reads only// the two// cells before it.func rob(nums []int) int { // BASE CASE: the best for "two back" and for "one back" prev2, prev1 := 0, 0 for _, x := range nums { // TRANSITION. SKIP x: the best stays prev1. // TAKE x: the house before x is not allowed, so add x to // prev2. cur := max(prev1, prev2+x) prev2, prev1 = prev1, cur // SHIFT } return prev1 // ANSWER: the best for all the houses}
Idea. The first house and the last house are neighbours, so one answer cannot have the two. Solve the line problem without the first house, then without the last house, and keep the larger result.
Complexity. Time O(n), space O(1).
Go lesson. A slice expression such as nums[1:] makes no copy. It is a new view of the same backing array, so the two calls cost no extra memory.
Step 3: the Go solution
// rob solves LC 213. Time O(n), space O(1).// The circle makes the first house and the last house neighbours.// So solve the line problem (LC 198) two times: without the first// house,// without the last.func rob(nums []int) int { n := len(nums) if n == 1 { return nums[0] // one house: the two views below are empty } // nums[1:] drops the first house. nums[:n-1] drops the last // house. return max(robLine(nums[1:]), robLine(nums[:n-1]))}// robLine is LC 198, the houses in a line.// STATE: dp[i] = the most money from the first i houses.// BASE CASE: dp[0] = 0.// TRANSITION: dp[i] = max(dp[i-1], dp[i-2] + nums[i-1]). SKIP house// i, or// TAKE it.// ANSWER: dp[n].// The two variables compress the table dp[0..n].func robLine(nums []int) int { prev2, prev1 := 0, 0 // BASE CASE for _, x := range nums { // TRANSITION: SKIP x, or TAKE x on top of "two back" cur := max(prev1, prev2+x) prev2, prev1 = prev1, cur // SHIFT } return prev1 // ANSWER}
Idea. Each palindrome has a centre. Try each centre, move the two ends out while the letters are equal, and keep the longest result.
Complexity. Time O(n²), space O(1).
Go lesson. A function can return two values, such as (start, length). A substring s[a:b] shares the memory of s, so it costs no copy.
Step 3: the Go solution
// longestPalindrome solves LC 5. Time O(n²), space O(1).// This solution is not a table DP. A table also works: dp[i][j] =// true if// s[i..j] is a// palindrome, with dp[i][j] = (s[i] == s[j] && dp[i+1][j-1]). It// needs// O(n²) memory.// The centre version has the same time and needs no table.func longestPalindrome(s string) string { bestStart, bestLen := 0, 0 for centre := 0; centre < len(s); centre++ { // ODD length: one letter is the centre, as in "aba". if start, length := expand(s, centre, centre); length > bestLen { bestStart, bestLen = start, length } // EVEN length: the centre is the gap between two letters, // as in // "abba". if start, length := expand(s, centre, centre+1); length > bestLen { bestStart, bestLen = start, length } } // the substring shares the bytes of s return s[bestStart : bestStart+bestLen]}// expand moves left and right out while they hold equal letters.// It returns the start and the length of the palindrome that it// found.func expand(s string, left, right int) (int, int) { // CHECK the limits first: && stops before s[left] can be out of // range. for left >= 0 && right < len(s) && s[left] == s[right] { left-- // EXPAND one step on each side right++ } // The loop stops one step too far on each side. // So the palindrome is s[left+1 .. right-1], and its length is // right-left-1. return left + 1, right - left - 1}
Idea. Each palindrome has one centre. From each centre, each step out that still has equal ends is one more palindrome, so count the steps.
Complexity. Time O(n²), space O(1).
Go lesson.s[i] is a byte, and two bytes compare with ==. The input has only lower-case English letters, so bytes are sufficient and runes are not necessary.
Step 3: the Go solution
// countSubstrings solves LC 647. Time O(n²), space O(1).// This solution is not a table DP. A table also works: dp[i][j] =// true if// s[i..j] is a// palindrome, and the answer is the number of true cells. It needs// O(n²)// memory.func countSubstrings(s string) int { count := 0 for centre := 0; centre < len(s); centre++ { // ODD length: one letter is the centre count += countFrom(s, centre, centre) // EVEN length: the centre is a gap count += countFrom(s, centre, centre+1) } return count}// countFrom counts the palindromes that have their centre between// left and// right.func countFrom(s string, left, right int) int { count := 0 // CHECK the limits first: && stops before s[left] can be out of // range. for left >= 0 && right < len(s) && s[left] == s[right] { count++ // s[left..right] is a palindrome left-- // EXPAND one step on each side right++ } return count}
Idea. The last letter of a prefix uses one digit or two digits. Add the ways of the shorter prefix for each of the two choices that is valid.
Complexity. Time O(n), space O(n).
Go lesson.s[i] is a byte, not a number. int(s[i]-'0') changes the digit character into its value.
Step 3: the Go solution
// numDecodings solves LC 91. Time O(n), space O(n).// STATE: dp[i] = the number of ways to decode the first i digits of// s.// BASE CASE: dp[0] = 1. The empty prefix has one way: write// nothing.// TRANSITION: dp[i] += dp[i-1] if the last digit is 1 to 9.// dp[i] += dp[i-2] if the last two digits are 10 to 26.// ANSWER: dp[n].func numDecodings(s string) int { n := len(s) dp := make([]int, n+1) // n+1 cells: dp[0] is the empty prefix dp[0] = 1 // BASE CASE for i := 1; i <= n; i++ { // The prefix of length i ends at s[i-1], not at s[i]. // ONE DIGIT: 1 to 9 is a letter, and 0 alone is not if s[i-1] != '0' { dp[i] += dp[i-1] } // TWO DIGITS: the prefix must have two digits or more if i >= 2 { // the last two digits as a number two := int(s[i-2]-'0')*10 + int(s[i-1]-'0') // "06" is 6, and that is not valid if two >= 10 && two <= 26 { dp[i] += dp[i-2] } } // If the two tests fail, dp[i] stays 0. A longer prefix // then gets 0 // from it. } return dp[n] // ANSWER}
Idea. The best way to make an amount ends with one last coin. Try each coin as the last coin, and add 1 to the best answer for the amount that stays.
Complexity. Time O(amount * n) for n coins, space O(amount).
Go lesson.make([]int, n) fills the slice with 0. Here 0 is a real answer, so the code writes a value for “not reached” into each cell first.
Step 3: the Go solution
// coinChange solves LC 322. Time O(amount * n) for n coins, space// O(amount).// STATE: dp[a] = the fewest coins that make the amount a.// BASE CASE: dp[0] = 0. The amount 0 needs no coin.// TRANSITION: dp[a] = min(dp[a-c] + 1) for each coin c that is not// larger// than a.// ANSWER: dp[amount], or -1 if no set of coins makes the amount.func coinChange(coins []int, amount int) int { // A real answer has amount coins at most (all coins of value // 1). // So amount+1 means "not reached". It is small, so +1 cannot // overflow. unreachable := amount + 1 // amount+1 cells, so dp[amount] exists dp := make([]int, amount+1) // BASE CASE (make already wrote 0, this line shows it) dp[0] = 0 for a := 1; a <= amount; a++ { dp[a] = unreachable for _, c := range coins { // TRY each coin as the LAST coin if c <= a { // the coin must fit // TRANSITION: the best for a-c, plus this one coin. // If dp[a-c] is not reached, the sum is too large // and min // ignores it. dp[a] = min(dp[a], dp[a-c]+1) } } } if dp[amount] == unreachable { return -1 } return dp[amount] // ANSWER}
Idea. A negative number changes the smallest product into the largest product. So keep two values for the subarrays that end at i: the largest product and the smallest product.
Complexity. Time O(n), space O(1).
Go lesson. The built-in max and min accept three values. Calculate the two products before you assign curMax, because the line for curMin needs the old curMax.
Step 3: the Go solution
// maxProduct solves LC 152. Time O(n), space O(1).// STATE: maxEnd[i] = the largest product of a subarray that ENDS at// index// i.// minEnd[i] = the smallest product of a subarray that ENDS at index// i.// BASE CASE: maxEnd[0] = minEnd[0] = nums[0].// TRANSITION: the subarray starts again at x = nums[i], or x// extends// maxEnd[i-1],// or x extends minEnd[i-1]. maxEnd[i] is the max of the three,// minEnd[i] is// the min.// ANSWER: the maximum of maxEnd[i] over all i.// The two variables compress the two tables: index i reads only// index i-1.func maxProduct(nums []int) int { curMax, curMin := nums[0], nums[0] // BASE CASE best := nums[0] for i := 1; i < len(nums); i++ { x := nums[i] // Calculate the two products from the OLD values, before an // assignment. extendMax := curMax * x // negative * negative can be the new largest product extendMin := curMin * x // TRANSITION: START again at x, or EXTEND one of the two // products. // The value x alone also resets the product after a 0. curMax = max(x, extendMax, extendMin) curMin = min(x, extendMax, extendMin) // ANSWER: the best subarray can end at each index best = max(best, curMax) } return best}
Idea. A prefix can be split if it ends with a word from the dictionary and the part before that word can also be split. Try each word as the last word.
Complexity. Time O(n * m * k) for a string of length n and m words of length k at most, space O(n).
Go lesson.s[start:i] is a substring with no copy, and strings compare with ==. The loop needs no strings function.
Step 3: the Go solution
// wordBreak solves LC 139. Time O(n * m * k), space O(n).// STATE: dp[i] = true if the first i bytes of s can be split into// words of// the dictionary.// BASE CASE: dp[0] = true. The empty prefix needs no word.// TRANSITION: dp[i] = true if a word w is the end of s[:i] and// dp[i-len(w)]// is true.// ANSWER: dp[n].func wordBreak(s string, wordDict []string) bool { n := len(s) // n+1 cells: dp[0] is the empty prefix. make fills with false. dp := make([]bool, n+1) dp[0] = true // BASE CASE for i := 1; i <= n; i++ { // TRY each word as the LAST word of s[:i] for _, w := range wordDict { // the index where the last word must start start := i - len(w) // TRANSITION. && tests from left to right, so // s[start:i] is // safe: // the slice is read only when start >= 0. if start >= 0 && dp[start] && s[start:i] == w { dp[i] = true break // one way is sufficient for this prefix } } } return dp[n] // ANSWER}
Idea. Let each index be the last item of a subsequence. The best subsequence that ends at i extends the best one that ends at an earlier, smaller value.
Complexity. Time O(n²) for the table, O(n log n) for the version with binary search, space O(n).
Go lesson.sort.SearchInts(a, x) does a binary search on a sorted slice. It returns the first index where a[i] >= x, or len(a) if no such index exists.
Step 3: the Go solution
Imports for a local file:sort
// lengthOfLIS solves LC 300. Time O(n²), space O(n).// STATE: dp[i] = the length of the longest increasing subsequence// that ENDS// at index i.// BASE CASE: dp[i] = 1, because nums[i] alone is a subsequence.// TRANSITION: dp[i] = max(dp[j] + 1) for each j < i with nums[j] <// nums[i].// ANSWER: the maximum of dp[i] over all i. It is not dp[n-1].func lengthOfLIS(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 // strictly smaller: nums[i] can EXTEND that subsequence if nums[j] < nums[i] { dp[i] = max(dp[i], dp[j]+1) // TRANSITION } } // ANSWER: the best subsequence can end at each index best = max(best, dp[i]) } return best}// lengthOfLISFast solves LC 300 in O(n log n) time and O(n) space.// tails[k] = the smallest last value of an increasing subsequence// of length// k+1.// tails is always sorted, so a binary search finds the place of// each new// value.// tails is not a real subsequence. Only its length is the answer.func lengthOfLISFast(nums []int) int { tails := make([]int, 0, len(nums)) // length 0, capacity n for _, x := range nums { // the first index with tails[i] >= x i := sort.SearchInts(tails, x) if i == len(tails) { // x is larger than all the tails: one longer // subsequence tails = append(tails, x) } else { // x is a smaller last value for the length i+1 tails[i] = x } } return len(tails)}
Idea. Two equal parts mean that one subset adds up to half of the total. So the question is a subset sum with the target sum / 2.
Complexity. Time O(n * sum) for n numbers, space O(sum).
Go lesson.make([]bool, n) fills the slice with false. A loop that counts down uses sum-- and a >= test, the same as a loop that counts up.
Step 3: the Go solution
// canPartition solves LC 416. Time O(n * sum), space O(sum).// STATE: dp[sum] = true if a subset of the numbers seen so far adds// up to// sum.// BASE CASE: dp[0] = true. The empty subset adds up to 0.// TRANSITION: for each number x, dp[sum] = dp[sum] || dp[sum-x].// SKIP x, or// TAKE x.// ANSWER: dp[total / 2].// The row compresses the table dp[i][sum] for the first i numbers.// Row i// reads only row i-1.func canPartition(nums []int) bool { total := 0 for _, x := range nums { total += x } if total%2 != 0 { return false // an odd total cannot make two equal parts } target := total / 2 dp := make([]bool, target+1) // target+1 cells, all false dp[0] = true // BASE CASE // ITEMS in the outer loop: each number one time for _, x := range nums { // BACKWARDS: dp[sum-x] is on the left, and the loop did not // change // it yet. // So it is still the value WITHOUT x. A forward loop uses x // two // times. 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}