Why Dynamic Programming Feels Hard Until You Name the State
As the Ace Hired prep breakdown points out, candidates often stumble on dynamic programming because it looks like guessing magic formulas rather than applying a fixed data structure. On the NeetCode roadmap, 1D DP and 2D DP sit deliberately late in the graph so recursion habits settle first.
My rule in interviews is strict: never code an array loop until I write a one-sentence definition of the state. As CP-Algorithms notes in its DP introduction, dynamic programming simply avoids recomputing identical subproblems by caching results in a predictable lookup order.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
From 1D States to 2D Tables
1. 1D DP: one index summarizes the past
In a 1D problem, a single scalar index encodes everything future choices need to know:
- Prefix decision (House Robber): Define
dp[i]as maximum loot across houses0..i. At housei, either skip it (dp[i - 1]) or rob it (dp[i - 2] + nums[i]). - Budget decision (Coin Change): Define
dp[a]as minimum coins needed to total amounta. Because coins are reusable, iteratingafromcoinupward letsdp[a - coin]already reflect usingcoinearlier in the same pass.
When deriving a 1D recurrence in an interview, I often write the top-down recursive relation first (solve(i) with a memo dictionary or @functools.cache) if transitions are easier to reason about backward from the goal. Once the subproblem graph has zero cycles and the transition works on tiny inputs, converting to a bottom-up for loop drops recursion call overhead and sets up constant-space optimization whenever only dp[i - 1] and dp[i - 2] are referenced.
2. 2D DP: pairing two prefixes or an item index with budget
Whenever a recurrence needs two independent coordinates, such as prefix i of string s1 and prefix j of string s2, or prefix i of items with remaining weight w, move to 2D dp[i][j].
For Longest Common Subsequence (LCS), define dp[i][j] as the LCS length of s1[:i] and s2[:j]. Padding row 0 and column 0 with zeros represents empty prefixes cleanly:
- If
s1[i - 1] == s2[j - 1], both characters match and extend the diagonal:dp[i][j] = 1 + dp[i - 1][j - 1]. - Otherwise drop one character from either string:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).
Notice how Edit Distance (Levenshtein distance) reuses this exact same 2D dependency stencil (i - 1, j - 1), (i - 1, j), and (i, j - 1): on a match, cost stays dp[i - 1][j - 1]; on a mismatch, take 1 + min(replace, delete, insert), initializing row 0 and column 0 to j and i instead of zero.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Once the 2D table is correct, notice each row depends only on row i - 1 and row i. Storing one array dp[0..n] plus a single scalar prev_diag (holding the overwritten dp[j - 1] from the previous row) cuts space from to .
Working Python Code
Below are tested Python implementations for 1D coin_change, space-compressed 2D longest_common_subsequence, and knapsack_01 showing backward capacity iteration.
def coin_change(coins: list[int], amount: int) -> int:
inf = amount + 1
dp = [inf] * (amount + 1)
dp[0] = 0
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return -1 if dp[amount] == inf else dp[amount]
def longest_common_subsequence(text1: str, text2: str) -> int:
if len(text1) < len(text2):
text1, text2 = text2, text1
n = len(text2)
dp = [0] * (n + 1)
for ch1 in text1:
prev_diag = 0
for j, ch2 in enumerate(text2, start=1):
saved_up = dp[j]
if ch1 == ch2:
dp[j] = prev_diag + 1
else:
dp[j] = max(dp[j], dp[j - 1])
prev_diag = saved_up
return dp[n]
def knapsack_01(weights: list[int], values: list[int], capacity: int) -> int:
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for cap in range(capacity, w - 1, -1):
dp[cap] = max(dp[cap], dp[cap - w] + v)
return dp[capacity]
if __name__ == "__main__":
assert coin_change([1, 2, 5], 11) == 3
assert coin_change([2], 3) == -1
assert longest_common_subsequence("abcde", "ace") == 3
assert knapsack_01([1, 3, 4], [15, 20, 30], 4) == 35
print("coin_change([1,2,5], 11):", coin_change([1, 2, 5], 11))
print("lcs('abcde', 'ace'):", longest_common_subsequence("abcde", "ace"))
print("knapsack_01:", knapsack_01([1, 3, 4], [15, 20, 30], 4))Running this script produces:
coin_change([1,2,5], 11): 3
lcs('abcde', 'ace'): 3
knapsack_01: 35Complexity Analysis
| Pattern | Time Complexity | Full Table Space | Rolling Space |
|---|---|---|---|
Coin Change (amount , coins) | |||
| LCS (lengths ) | |||
| 0-1 Knapsack ( items, capacity ) |
Watch out for pseudo-polynomial runtime on knapsack and coin change: looks linear in , yet if while , DP blows time and memory limits immediately (that is a meet-in-the-middle or backtracking cue, not DP). Also remember to check whether swapping the shorter string into the inner column loop (if len(text1) < len(text2)) actually reduces working memory from down to when one input string is drastically longer than the other, since O(m) vs O(n) matters under tight memory budgets.
Common Mistakes and When I Skip Bottom-Up Compression
Four mistakes cause almost every DP bug I review:
- Forward loop on 0-1 knapsack: Looping
capfromwtocapacityin 1D lets the same item get picked multiple times. Always loop backward (range(capacity, w - 1, -1)) for 0-1 constraints, and forward for unbounded reuse. - Overwriting `dp[j - 1]` before saving `prev_diag`: Without
saved_up = dp[j]before mutatingdp[j], diagonal LCS and edit-distance transitions read the current row instead of rowi - 1. - Using `float("inf")` carelessly in integer arrays: Sentinel
amount + 1stays an integer without floating-point conversions, making min checks clean and fast. - Forgetting state order in counting combinations vs permutations: In Coin Change II (number of ways), outer-looping coins counts combinations, while outer-looping amounts counts order-dependent permutations.
I skip 1D space compression in two concrete situations: when the interviewer asks to reconstruct the actual chosen subsequence or path (rebuilding requires the full 2D table or explicit parent pointers), and during the first pass in a 45-minute interview, where writing the clean 2D table first avoids indexing bugs and space optimization becomes a crisp 2-minute follow-up.
Practice Problems
Practice both 1D state modeling and 2D sequence alignment on these two benchmark problems:
- Coin Change: Implement bottom-up minimum coin counting with integer sentinel bounds and verify impossible amounts return
-1. - Longest Common Subsequence: Start with the
(m + 1) x (n + 1)2D table, then refactor to theO(min(m, n))rolling row usingprev_diag.
