2-D Dynamic Programming (LeetCode #14)
A 2-D table appears when the state needs two indices: two positions in two strings, a cell in a grid, or a range [i, j]. The recipe is the same as 1-D DP — define the state, write the recurrence, set boundaries, choose the fill order — but the order now matters. This post covers all 11 NeetCode 2-D DP problems.
The technique
Fill order. For dp[i][j] depending on dp[i-1][j] (above) and dp[i][j-1] (left), row-major works. For dp[i][j] depending on interior cells dp[i][k], dp[k][j], fill by increasing interval length.
Space. If each row needs only the row above and the current row, keep one array and update it in the correct direction.
Unique Paths
The question. Count monotone paths across an m × n grid (only right/down).
The idea. Arrive from above or the left, so dp[i][j] = dp[i-1][j] + dp[i][j-1]; the first row/column are 1.
def unique_paths(m, n):
dp = [1] * n
for _ in range(1, m):
for j in range(1, n):
dp[j] += dp[j - 1] # above (old) + left (new)
return dp[-1]
\(O(mn)\) time, \(O(n)\) space. See Unique Paths.
Longest Common Subsequence
The question. Length of the longest common subsequence of two strings.
\[ dp[i][j] = \begin{cases} dp[i-1][j-1] + 1 & a[i-1] = b[j-1] \\ \max(dp[i-1][j], dp[i][j-1]) & \text{otherwise} \end{cases} \]
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
\node[c, fill=blue!6] at (0,0.62) {}; \node[c, fill=blue!6] at (-0.66,0.62) {2}; \node[c, fill=blue!6] at (0,1.24) {2};
\node[c, fill=green!20] at (0,0) {3};
\draw[->, thick] (-0.66,0.62) -- (0,0.15);
\draw[->, thick] (0,1.24) -- (0,0.62);
\draw[->, thick, green!55!black] (-0.66,1.24) -- (-0.15,0.5);
\node[font=\scriptsize\ttfamily, text=green!45!black, anchor=west] at (0.35,0.9) {match: diagonal + 1};
\node[font=\scriptsize\ttfamily, anchor=west] at (0.35,0.35) {else: best of up / left};
\end{tikzpicture}
def lcs(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1] + 1
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
\(O(mn)\).
Best Time to Buy and Sell Stock with Cooldown
The question. Buy/sell with a one-day cooldown after selling; maximise profit.
The idea. Three states per day: hold (own a stock), sold (just sold, on cooldown), rest (not holding, free). Transitions:
- hold:
max(prev_hold, prev_rest - price) - sold:
prev_hold + price - rest:
max(prev_rest, prev_sold)
Answer is max(sold, rest).
Walk it through on [1,2,3,0,2]: buy at 1, sell at 2 (profit 1), rest day 3 (cooldown), buy at 0, sell at 2 → total 3.
def max_profit_cooldown(prices):
hold, sold, rest = float("-inf"), 0, 0
for p in prices:
prev_sold = sold
sold = hold + p
hold = max(hold, rest - p)
rest = max(rest, prev_sold)
return max(sold, rest)
\(O(n)\) time, \(O(1)\) space.
Coin Change II
The question. Count the number of combinations of coins that sum to amount (order does not matter).
Input: amount = 5, coins = [1,2,5] -> 4
The idea. 0/1-style DP over coins. dp[a] = number of ways to make a. For each coin, iterate a upward so the coin can be reused, adding dp[a - coin].
def change(amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for a in range(coin, amount + 1): # upward: unbounded reuse
dp[a] += dp[a - coin]
return dp[amount]
Order of loops matters: coins outer counts combinations (order ignored); amount outer would count permutations.
\(O(\text{amount} \times \text{coins})\).
Target Sum
The question. Assign +/- to each number; count the ways to reach target.
Input: nums = [1,1,1,1,1], target = 3 -> 5
The idea. Assigning signs splits the numbers into a + set P and a - set N, with sum(P) - sum(N) = target. Since sum(P) + sum(N) = total, we get sum(P) = (total + target) / 2. So count subsets summing to that — a 0/1 knapsack.
Walk it through on nums = [1,1,1,1,1], target = 3. Then total = 5 and goal = (5+3)/2 = 4: we need subsets of sum 4, i.e. choosing which four of the five ones are + — there are \(\binom{5}{4} = 5\). The dp array (dp[s] = ways to reach s) evolves downward so each number is used once:
start: [1, 0, 0, 0, 0]
after 1st 1: [1, 1, 0, 0, 0]
after 2nd 1: [1, 2, 1, 0, 0]
after 3rd 1: [1, 3, 3, 1, 0]
after 4th 1: [1, 4, 6, 4, 1]
after 5th 1: [1, 5, 10, 10, 5] -> dp[4] = 5
def find_target_sum_ways(nums, target):
total = sum(nums)
if (total + target) % 2 or abs(target) > total:
return 0
goal = (total + target) // 2
dp = [0] * (goal + 1)
dp[0] = 1
for x in nums:
for s in range(goal, x - 1, -1): # downward: use once
dp[s] += dp[s - x]
return dp[goal]
Why the two pre-checks. total + target must be even, otherwise goal is fractional and no sign split exists. abs(target) > total is impossible even with all signs aligned, so return 0 immediately.
Why downward. Iterating s from goal down to x reads dp[s-x] from this round’s already-updated values without reusing x twice — the 0/1 constraint. Upward would let x be spent repeatedly.
Complexity. \(O(n \cdot \text{goal})\) time, \(O(\text{goal})\) space.
Edge cases. target = 0 counts signings that balance out. Zeros in nums double every count (each zero can be +0 or -0); the DP handles this because dp[s] += dp[s-0] doubles dp[s].
Interleaving String
The question. Can s3 be formed by interleaving s1 and s2 while preserving their internal order?
Input: s1 = "aab", s2 = "axy", s3 = "aaxaby" -> True
The idea. dp[i][j] = can the first i of s1 and first j of s2 form the first i+j of s3? The next character of s3 must come from s1 or s2.
Walk it through on s1 = "aab", s2 = "axy", s3 = "aaxaby". Cell (i,j) checks s3[i+j-1] against s1[i-1] (from above) or s2[j-1] (from the left):
j: "" a x y
i="": T T . .
i=a: T T T .
i=aa: T . T .
i=aab: . . T T
For example, (1,2) is True because s3[2] = x matches s2[1] = x and (1,1) is True; (2,1) is False because s3[2] = x matches neither s1[1] = a nor s2[0] = a. Reading the last cell gives True.
def is_interleave(s1, s2, s3):
if len(s1) + len(s2) != len(s3):
return False
dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
dp[0][0] = True
for i in range(len(s1) + 1):
for j in range(len(s2) + 1):
if i and s1[i-1] == s3[i+j-1]:
dp[i][j] |= dp[i-1][j]
if j and s2[j-1] == s3[i+j-1]:
dp[i][j] |= dp[i][j-1]
return dp[-1][-1]
Why the length check first. Interleaving preserves total length, so mismatched lengths can return False before building the table. Inside, s3’s index i+j-1 is forced — i characters from s1 plus j from s2 consume exactly i+j of s3.
Complexity. \(O(mn)\) time and space.
Edge cases. Empty s1 or s2 reduces to an equality check. Duplicate letters are fine; both branches are tried via |= when both match.
Longest Increasing Path in a Matrix
The question. Return the longest strictly increasing path in a matrix (moving 4-directionally).
The idea. This is DFS with memoization: dfs(r, c) is the longest increasing path starting at (r, c), equal to 1 + max over neighbours with a larger value. Memoize so each cell is computed once.
Walk it through on [[9,9,4],[6,6,8],[2,1,1]] (answer 4: 1 → 2 → 6 → 9). Memoized lengths by cell:
9:1 9:1 4:2
6:2 6:2 8:1
2:3 1:4 1:2
From (2,1) = 1 the only larger neighbours are (2,0) = 2 (length 3) and (1,1) = 6 (length 2), so dfs(2,1) = 1 + 3 = 4. The chain realizing it is (2,1) → (2,0) → (1,0) → (0,0). Every other cell’s value is found by the same rule — (0,2) = 4 sees larger neighbours (1,2) = 8 and (0,1) = 9, both length 1, so it is 2 — and no cycle is possible because values strictly increase along every call.
def longest_increasing_path(matrix):
if not matrix:
return 0
rows, cols = len(matrix), len(matrix[0])
memo = {}
def dfs(r, c):
if (r, c) in memo:
return memo[(r, c)]
best = 1
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = r+dr, c+dc
if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
best = max(best, 1 + dfs(nr, nc))
memo[(r, c)] = best
return best
return max(dfs(r, c) for r in range(rows) for c in range(cols))
Why memoization makes it linear. Without it, the same increasing chain is rewalked from every cell on it — exponential. With it, each cell’s outgoing edges are explored once and its answer reused, giving \(O(R \cdot C)\) edge work total.
Why no visited set is needed. The strict > forces progress along increasing values, so a recursion cycle is impossible and backtracking-style unmarking is unnecessary.
Complexity. \(O(R \cdot C)\) time and space.
Edge cases. Empty matrix → 0. All equal values → 1. The outer max checks every cell because the longest path may start anywhere, not just at a minimum.
Distinct Subsequences
The question. Count the number of distinct subsequences of s equal to t.
Input: s = "rabbbit", t = "rabbit" -> 3
The idea. dp[i][j] = ways to form t[:j] from s[:i]. If s[i-1] == t[j-1], we may use this character (add dp[i-1][j-1]) or skip it (dp[i-1][j]); otherwise only skip.
def num_distinct(s, t):
dp = [0] * (len(t) + 1)
dp[0] = 1
for ch in s:
for j in range(len(t), 0, -1): # downward: use each s char once
if ch == t[j-1]:
dp[j] += dp[j-1]
return dp[-1]
\(O(mn)\) time, \(O(n)\) space.
Edit Distance
The question. Minimum insert/delete/replace to turn a into b.
The idea. dp[i][j] is the distance between the prefixes a[:i] and b[:j]. Boundaries are pure deletions/insertions (dp[i][0] = i, dp[0][j] = j). If the last characters match, the answer is the inner distance; otherwise pay 1 for the cheapest of delete (dp[i-1][j]), insert (dp[i][j-1]), or replace (dp[i-1][j-1]).
Walk it through on a = "horse", b = "ros" (answer 3):
"" r o s
"" 0 1 2 3
h 1 1 2 3
o 2 2 1 2
r 3 2 2 2
s 4 3 3 2
e 5 4 4 3
Step o→o copies the diagonal (dp[2][2] = dp[1][1] = 1), and the final e→s mismatch takes 1 + min(dp[4][3], dp[5][2], dp[4][2]) = 1 + 2 = 3.
def edit_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1): dp[i][0] = i
for j in range(n + 1): dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1]
else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[m][n]
Why the three neighbours. Deleting a[i-1] costs the distance of the shorter pair plus 1 (dp[i-1][j] + 1); inserting b[j-1] likewise from dp[i][j-1]; replacing costs the diagonal plus 1. The min picks the cheapest last operation, and a match makes it free.
Complexity. \(O(mn)\) time and space (reducible to \(O(n)\) space with two rolling rows).
Edge cases. One string empty → the other’s length. Identical strings → 0 (the whole diagonal copies).
Burst Balloons
The question. Burst balloons for left × self × right points (neighbours are the nearest unburst balloons). Maximise the total.
The idea — burst LAST. If balloon k is burst last in [i, j], its neighbours are the boundaries i-1 and j+1, and the subintervals are independent. Fill by increasing interval length.
Walk it through on nums = [3,1,5,8] (answer 167), with vals = [1,3,1,5,8,1]. Length-1 coins are trivial; length-2 intervals already combine: dp[2][3] = 3·5·8 + dp[2][2] = 120 + 15 = 135 (balloon 5… wait, dp[2][3] spans balloons 1, 5 with bounds 3, 8: bursting 5 last gives 3·5·8 = 120 plus dp[2][2] = 3·1·5 = 15).
The final interval dp[1][4] tries every balloon last (bounds are the sentinel 1s):
last k |
points vals[i-1]·vals[k]·vals[j+1] |
plus subproblems | total |
|---|---|---|---|
| 1 (value 3) | 1·3·1 |
+ dp[2][4] = 159 |
162 |
| 2 (value 1) | 1·1·1 |
+ dp[1][1] + dp[3][4] = 3 + 48 |
52 |
| 3 (value 5) | 1·5·1 |
+ dp[1][2] + dp[4][4] = 30 + 40 |
75 |
| 4 (value 8) | 1·8·1 |
+ dp[1][3] = 159 |
167 |
So the optimum bursts 8 last (8 points) after collecting 159 from [3,1,5] — itself optimal by bursting 3 last there (1·3·8 = 24 plus dp[2][3] = 135; and dp[2][3] reaches 135 by bursting 5 last, 3·5·8 = 120 plus dp[2][2] = 3·1·5 = 15).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt},
a/.style={->, thick}]
\node[c, fill=blue!8] (b1) at (0,0) {1}; \node[c, fill=blue!8] (b5) at (1.5,0) {5}; \node[c, fill=orange!25] (b8) at (3.0,0) {8};
\draw[a] (b1) to[bend left=25] (b5);
\node[font=\scriptsize\ttfamily, anchor=north] at (0.75,-0.4) {135};
\draw[a, orange!80!black] (0.4,-0.9) to[bend right=20] (2.6,-0.9);
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.5,-1.2) {burst 8 last: +8};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.5,-1.7) {neighbours pinned to the boundaries};
\end{tikzpicture}
``` Unrolled, the order is: 1 (`3·1·5 = 15`), 5 (`3·5·8 = 120`), 3 (`1·3·8 = 24`), 8 (`1·8·1 = 8`) — totalling 167.
```python
def max_coins(nums):
vals = [1] + nums + [1]
n = len(vals)
dp = [[0] * n for _ in range(n)]
for length in range(1, n - 1):
for i in range(1, n - length):
j = i + length - 1
for k in range(i, j + 1):
dp[i][j] = max(dp[i][j],
vals[i-1]*vals[k]*vals[j+1] + dp[i][k-1] + dp[k+1][j])
return dp[1][n-2]
Why bursting last fixes the neighbours. Bursting first changes who is adjacent to whom as neighbours collapse — the subproblems are not independent. Bursting k last means everything inside [i,j] except k is already gone, so k’s neighbours are pinned to the boundaries; the left and right subintervals then decompose cleanly.
Why length order. dp[i][j] needs the strictly shorter intervals on both sides, so filling by increasing length guarantees everything is ready.
Complexity. \(O(n^3)\) time (intervals × split points), \(O(n^2)\) space.
Edge cases. One balloon → 1·x·1 = x. Zeroes burst for free and split the array naturally.
Regular Expression Matching
The question. Match . (any char) and * (zero or more of the preceding element).
The idea. dp[i][j] = do s[:i] and p[:j] match? A * means either drop x* entirely (dp[i][j-2]) or keep matching one more character if x fits s[i-1] (dp[i-1][j]); a plain character or . just steps both diagonally.
Walk it through on s = "aab", p = "c*a*b" (answer True):
"" c * a * b
"" T F T F T F
a F F F T T F
a F F F F T F
b F F F F F T
c* matches empty via dp[0][2] = dp[0][0], so a* inherits emptiness at dp[0][4]. The a at (1,3) then copies that diagonal, (1,4) reuses it through a*… and the final b steps from dp[2][4], which held because the double-a was consumed by a*.
def is_match(s, p):
m, n = len(s), len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for j in range(1, n + 1):
if p[j-1] == "*":
dp[0][j] = dp[0][j-2] # "x*" matches empty
for i in range(1, m + 1):
for j in range(1, n + 1):
if p[j-1] == "*":
dp[i][j] = dp[i][j-2] or (dp[i-1][j] and p[j-2] in (s[i-1], "."))
elif p[j-1] in (s[i-1], "."):
dp[i][j] = dp[i-1][j-1]
return dp[m][n]
Why dp[i-1][j] for star extension. Matching one more s[i-1] with x* keeps the pattern at the same j — the star stays “open” — so the state reads the row above. Skipping the star (dp[i][j-2]) closes it. Together these cover every way x* can consume characters.
Why the first row needs its own loop. dp[0][j] has no row above, so only the zero-consumption rule applies: a* (or chains like c*a*) can still match the empty string.
Complexity. \(O(mn)\) time and space.
Edge cases. Pattern starting with * is invalid input (nothing precedes it). Consecutive stars like a** are invalid by the same rule. . matches any single character exactly once — multiplicity needs an accompanying *.
Pitfalls
- Wrong fill order. Interval DP fills by length.
- Missing base rows/columns. Most bugs live there.
- Coin Change II loop order. Coins outer → combinations; amount outer → permutations.
- Target Sum not reducing to subset-sum. Derive
sum(P) = (total + target)/2first. - Using “burst first” in Burst Balloons. Only “burst last” decomposes the interval.
Why must Burst Balloons fill by interval length? Why does loop order matter in Coin Change II?
ASolution
dp[i][j] depends on shorter interior intervals, so filling by increasing length guarantees they are ready. In Coin Change II, iterating coins in the outer loop counts each combination once (order ignored); iterating the amount outer would count different orderings separately, giving permutations instead.
Next: Greedy (LeetCode #15) — the locally best choice, provably.