Grid & 2D DP
What is this?
Some problems need two indices instead of one โ your position in a grid, or how much of each of two strings you have used so far. Here each answer lives in a 2D table dp[i][j] and is built from a few nearby cells you already filled, like figuring out the cheapest path to a square from the squares just above and to its left. Once a cell is computed it is remembered, so the whole table fills in one sweep without ever redoing a square.
๐ก Fun fact: The two-string version of this table is the engine behind tools you use daily โ
git diff, spell-checkers, and DNA sequence aligners all compute a longest-common-subsequence or edit-distance grid exactly like the ones in this chapter.
๐ The 7 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: When the state needs two indices โ a position in a grid, or a prefix of each of two strings โ the DP becomes a 2D table
dp[i][j]filled from neighboring cells. Almost every famous string/grid DP is the same loop with a different "combine" rule: add the neighbors, take the min of three, or extend the diagonal on a match.
One loop, different combine rules
Get the base row/column and the direction of dependency right, and a cell just reads already-computed neighbors. Then collapse the table to a rolling row for O(n) space.
The problems
- Unique Paths โ the gentle intro: paths = from above + from left.
- Maximal Square / Minimum Falling Path Sum โ min-of-neighbors recurrences over a grid.
- Paint House โ
dp[i][color]with an adjacency constraint; state = your last choice. - Edit Distance, Longest Common Subsequence, Wildcard Matching โ the two-string family: matches glide diagonally; the rest is the per-problem rule (3 operations, max-align, or
*'s two transitions).
Key takeaways
- Two indices โ a 2D table; each cell combines a handful of neighbors.
- The family shares one loop โ only the combine rule and base cases change.
- Matches move diagonally in two-string DPs (LCS, Edit Distance); mismatches branch.
- Collapse to a rolling row for O(min(m,n)) space once it works.
- Why interviewers love it: the 2D table is the most reused DP shape in real interviews (diff, alignment, grids).
Start here: Unique Paths (the template), then Longest Common Subsequence and Edit Distance.
Longest Common Subsequence
Core idea: Walk both strings from the back, comparing the last characters of two prefixes. If they match, that shared character is part of the answer โ keep it and recurse on the two shorter prefixes (the diagonal,
+1). If they don't match, at least one of those two last characters is useless for this pairing, so throw away one (from either string) and take whichever choice leaves the longer common subsequence. Cache the answer for every(prefix-of-1, prefix-of-2)pair and the exponential search collapses into anm ร ntable.
Problem, rephrased
Forget the textbook phrasing. Here's the scenario:
Two editors typed up the same paragraph independently, then each made their own edits โ inserting, deleting, and rearranging nothing but keeping the original word order intact. You want to measure how much of the original survived in both versions: the longest run of characters (not necessarily next to each other, but in the same relative order) that appears in both texts.
Formally: given two strings text1 and text2, return the length of their longest common subsequence. A subsequence is what's left after deleting zero or more characters without reordering the rest โ so "ace" is a subsequence of "abcde" (delete b and d), but "aec" is not (wrong order). A common subsequence is one that's a subsequence of both strings. If there is no common subsequence, the answer is 0.
text1 |
text2 |
LCS length | A longest common subsequence |
|---|---|---|---|
"abcde" |
"ace" |
3 |
"ace" |
"abc" |
"abc" |
3 |
"abc" (identical strings) |
"abc" |
"def" |
0 |
"" (nothing in common) |
Note we return the length, not the subsequence itself (though the table can reconstruct one โ more on that below). Let m = len(text1) and n = len(text2).
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson