DP on grids and sequences
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Define a two-dimensional DP state for grid problems.
- Distinguish subsequences from substrings when modelling a state.
- Reduce a DP table to rolling rows to save space.
Overview
#Grids: state as a cell
For a grid where you move only right or down, the state is the number of ways to reach a cell. The transition adds the ways from the cell above and the cell to the left:
function uniquePaths(rows, cols) {
const dp = Array.from({ length: rows }, () => new Array(cols).fill(1));
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
}
}
return dp[rows - 1][cols - 1];
}
The first row and column have exactly one way each, which is why they start at 1.
Sequence: subsequence versus substring
A subsequence keeps order but may skip elements; a substring must be contiguous. This choice changes the state.
For the longest increasing subsequence, dp[i] is the length of the longest increasing subsequence ending at index i. The transition looks back at every earlier index with a smaller value:
function lis(values) {
const dp = new Array(values.length).fill(1);
let best = 0;
for (let i = 0; i < values.length; i++) {
for (let j = 0; j < i; j++) {
if (values[j] < values[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
best = Math.max(best, dp[i]);
}
return best;
}
This is O(n^2). A patience-sorting approach with binary search reduces it to O(n log n).
Rolling rows
If a state depends only on the previous row, keep one row and update it in place with care for the direction of the dependency. This turns O(rows * cols) space into O(cols).
Reading a DP problem
Ask three questions: what is the state, what is the transition, and what are the base cases? Write the answers as comments before coding. Most DP bugs are a wrong state or a missing base case, not a coding slip.
Practice next
- Count the ways to reach the bottom-right of a grid with obstacles.
- Explain how to reduce the LIS table to a single array.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
How many unique paths exist from the top-left to the bottom-right of a 3 by 3 grid moving only right or down?
starter.javascript// dp[r][c] = dp[r-1][c] + dp[r][c-1]Reveal the reference answer
reference.javascriptThe bottom-right cell of the 3 by 3 table is 6. There are six monotone paths.Authored expected output: 6
Each cell sums the ways from above and from the left.
Exercise 2Predict
What is the longest increasing subsequence length of [10, 9, 2, 5, 3, 7, 101, 18]?
starter.javascript// dp[i] = longest increasing subsequence ending at iReveal the reference answer
reference.javascriptOne longest increasing subsequence is [2, 3, 7, 101] with length 4. So the answer is 4.Authored expected output: 4
The subsequence need not be contiguous, only increasing in order.
Exercise 3Explain
Explain how to reduce a grid DP table to a single row.
Reveal the reference answer
reference.textIf each cell depends only on the cell above and the cell to the left, you can keep one row. Update left to right so the left value is the current row and the value still in the array at the same column is the previous row. Overwrite each cell with the sum. This keeps O(cols) space instead of O(rows * cols).Authored expected output: Keep one row updated left to right, reusing the previous-row value in place.
Rolling arrays are a standard DP space optimisation.
Common misconceptions
#- Subsequence and substring are the same. Subsequence may skip elements; substring is contiguous.
- A larger DP table is always needed. Rolling rows often reduce space without changing the answer.
- The base cases are optional. A missing or wrong base case silently corrupts every later state.
Follow-up practice
#- dsa-from-zero-greedy-and-intervals
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.