Data Structures and Algorithms5 min read

Dynamic Programming From 1D States to 2D Grids and Space Compression

A repeatable workflow for deriving 1D and 2D dynamic programming recurrences from overlapping subproblems, avoiding unbounded vs 0-1 loop direction bugs, and compressing 2D tables to 1D memory.

Dynamic programming solves optimization and counting problems with overlapping subproblems by defining a minimal state, a recurrence linking smaller solved states, and base cases. Moving from 1D sequences to 2D grids simply adds a second index for a pair of strings or remaining budget, and rolling-row compression drops 2D space to O(min(m, n)) whenever transitions depend only on the previous row.

Key takeaways

  • Never jump straight to a 1D space trick during an interview before verifying the 2D recurrence first.
  • Name what dp[i] or dp[i][j] means in plain English before writing a single transition line.
  • Compare top-down memoization recursion limits against bottom-up iteration when constraints reach 10^5.

Quick facts

  • Unbounded coin change iterates amounts forward so each coin can contribute multiple times.
  • Zero-one knapsack in 1D iterates capacity backward so each item contributes at most once per step.
  • Longest Common Subsequence uses a (m + 1) x (n + 1) padded table to remove empty-string branches.
  • Saving prev_diag before overwriting dp[j] lets 2D grid recurrences compress cleanly into a single row.

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.

Dynamic programming transition stencil from 1D state array to 2D table and rolling row
Dynamic programming transition stencil from 1D state array to 2D table and rolling row

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 houses 0..i. At house i, 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 amount a. Because coins are reusable, iterating a from coin upward lets dp[a - coin] already reflect using coin earlier 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:

  1. If s1[i - 1] == s2[j - 1], both characters match and extend the diagonal: dp[i][j] = 1 + dp[i - 1][j - 1].
  2. 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.

2D DP table for Longest Common Subsequence of abcde and ace
2D DP table for Longest Common Subsequence of abcde and ace

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 O(mn)O(mn) to O(min⁡(m,n))O(\min(m, n)).

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.

PYTHON
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:

TEXT
coin_change([1,2,5], 11): 3
lcs('abcde', 'ace'): 3
knapsack_01: 35

Complexity Analysis

PatternTime ComplexityFull Table SpaceRolling Space
Coin Change (amount AA, kk coins)O(A⋅k)O(A \cdot k)O(A)O(A)O(A)O(A)
LCS (lengths m,nm, n)O(m⋅n)O(m \cdot n)O(m⋅n)O(m \cdot n)O(min⁡(m,n))O(\min(m, n))
0-1 Knapsack (NN items, capacity WW)O(N⋅W)O(N \cdot W)O(N⋅W)O(N \cdot W)O(W)O(W)

Watch out for pseudo-polynomial runtime on knapsack and coin change: O(N⋅W)O(N \cdot W) looks linear in WW, yet if W=109W = 10^9 while N=30N = 30, 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 O(m)O(m) down to O(min⁡(m,n))O(\min(m, n)) 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 cap from w to capacity in 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 mutating dp[j], diagonal LCS and edit-distance transitions read the current row instead of row i - 1.
  • Using `float("inf")` carelessly in integer arrays: Sentinel amount + 1 stays 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:

  1. Coin Change: Implement bottom-up minimum coin counting with integer sentinel bounds and verify impossible amounts return -1.
  2. Longest Common Subsequence: Start with the (m + 1) x (n + 1) 2D table, then refactor to the O(min(m, n)) rolling row using prev_diag.

Sources