Dynamic Programming Course Intro


Dynamic Programming Course Intro

Anna
Dynamic programming has a reputation for being tough, but Alvin says it can be intuitive if we take a gradual approach. Instead of jumping into hard problems, we need to understand the fundamentals first.

Michael
Right. And it's essential for coding interviews. The course starts with Fibonacci, the classic recursive example. We'll write a function that returns the nth Fibonacci number, starting with base cases for n=1 and n=2.

Anna
Alvin walks through the recursive tree for fib(7). Each node branches into two recursive calls, forming a binary tree. The base cases are when n is 1 or 2, returning 1. Then we add up the children to get the result.

Michael
The problem is that this recursive version is incredibly slow for larger n. Alvin asks, why? It's because the tree has exponential size—roughly 2^n nodes. But let's be precise: the time complexity is O(2^n), and the space complexity is O(n) due to the call stack.

Anna
To really understand, he compares fib to two other functions: one that always subtracts 1 (dib) and one that always subtracts 2 (lib). Both have similar exponential time, but dib and lib help us see the branching factor and height clearly.

Michael
The key insight is that the recursive tree contains many duplicate subtrees. For example, fib(3) appears multiple times. That's the overlap we can exploit using memoization.

Anna
Memoization means we store results of function calls in an object keyed by the arguments. Then, before computing, we check if we already have the answer. This cuts down the time from exponential to linear—O(n) time and space.

Michael
Alvin implements it by adding a memo parameter with a default empty object. Inside fib, he checks if n is in memo, and if so, returns it. Otherwise, computes recursively, stores the result, and returns it. That small change makes fib(50) instantaneous.

Anna
Next is grid traveler: counting unique paths from top-left to bottom-right in an m×n grid, moving only down or right. The recursive brute force has a tree similar to Fibonacci but with two parameters: rows (m) and columns (n).

Michael
The brute force time complexity is O(2^(m+n)), which is exponential. But we can memoize using a key that combines m and n with a comma separator. After memoization, the time becomes O(m*n), a huge improvement.

Anna
Alvin gives a memoization recipe: first get a brute-force recursive solution (visualized as a tree), then add a memo object that maps arguments to return values, check it at the start, and store results before returning. The hard part is the recursion, not the memoization.

Michael
Then comes can sum: given a target sum and an array of numbers, can we make the target by adding numbers (reuse allowed)? Return true/false. The tree branches by subtracting each number from the current target. If we hit 0, it's true; if negative, false.

Anna
Brute force time: O(n^m) where m = target sum, n = array length. But memoization brings it to O(m*n). The key is just the target sum because the array never changes. Same pattern: check memo, store results.

Michael
How sum is similar but returns one combination that adds up to the target, or null if impossible. Recursively, when we hit 0, we return an empty array. Then we push the current number onto the result from the recursive call. Early return if we find any valid combination.

Anna
Memoization reduces the time from O(n^m * m) to O(m^2 * n). The space becomes O(m^2) due to storing arrays in the memo. But it's still polynomial and fast enough.

Michael
Best sum asks for the shortest combination that sums to the target. Here, we can't return early; we need to try all branches and keep the shortest array. The brute force is similar to how sum, but we maintain a 'shortest' variable that we update whenever we find a shorter combination.

Anna
Memoization works again: we add a memo object, check if target sum is known, store results. The complexity is the same as how sum: O(m^2 * n) time, O(m^2) space. The only difference is the conditional that prefers shorter arrays.

Michael
Now we move to string problems. Can construct: given a target string and an array of words, can we concatenate words to form the target? (Reuse allowed). The tree branches by removing matching prefixes from the target. Base case: empty string returns true.

Anna
The brute force is O(n^m * m) where m = target length, n = number of words. But memoization on the target string reduces it to O(m^2 * n). The key is just the target because the word bank stays the same.

Michael
Count construct returns the number of ways to form the target. Instead of true/false, we return 1 for empty string, 0 for dead ends, and sum the numbers from children. Memoization gives O(m^2 * n) time, O(m) space (just numbers in memo).

Anna
All construct is the hardest: return a 2D array of all combinations that form the target. The base case for empty string is [[]]. For impossible targets, it's []. We recursively get all ways for the suffix, then prepend the word to each way and combine.

Michael
Even with memoization, the worst-case time is exponential because the output itself can be exponential in size. So we can't do better than O(n^m). The space is also exponential due to the result. But memoization helps when the target is not reachable, avoiding redundant work.

Anna
Alvin then introduces a second major strategy: tabulation. Instead of recursion with memo, we build a table iteratively from the bottom up. For Fibonacci, we create an array of size n+1, fill with zeros, set index 1 to 1, then iterate: add current value to the next two positions.

Michael
Tabulation for fib gives O(n) time and space. For grid traveler, we create a 2D table of size (m+1)×(n+1) filled with zeros, set (1,1)=1, then iterate: add current value to right and down neighbors (if in bounds). Result is at (m,n).

Anna
For can sum with tabulation, we create a boolean table of size target+1, all false except index 0 = true. Then iterate: if at index i is true, for each num in numbers, set table[i+num] = true (if within bounds). Return table[target].

Michael
How sum tabulation: similar but table stores arrays or null. Initialize with null, set index 0 to []. Then whenever we update a position, we copy the current array and add the number. For best sum, we add a check: only update if the new combination is shorter.

Anna
For string problems, tabulation uses the target length. Table of size target.length+1. For can construct, we store booleans: index i represents prefix up to i. Start with index 0 = true. For each i, if true, for each word that matches at that position, set table[i+word.length] = true.

Michael
Count construct tabulation stores numbers, starting with 1 at index 0. When we find a matching word, we add table[i] to table[i+word.length]. All construct tabulation stores arrays of combinations: index 0 = [[]]. Then we append new combinations by extending existing ones.

Anna
Alvin wraps up by emphasizing that understanding the recursive tree and identifying overlapping subproblems is key. Whether you choose memoization or tabulation, the core is breaking the problem into smaller instances.

Michael
And always draw the strategy first! Visualizing the problem on a whiteboard makes everything clearer. Then implement the brute force recursion, add memoization, or build the table iteratively. With practice, it becomes second nature.

Ask anything
We've read this whole study set, so questions about it get the best answers.