SDE & MLE Prep

2-D DP

Common state shapes

  • Grid: dp[r][c] from dp[r-1][c], dp[r][c-1] (paths, min path sum, squares).
  • Two strings: dp[i][j] = answer for prefixes a[:i], b[:j] (LCS, edit distance, interleaving, regex).
  • Interval: dp[l][r] over a substring/subarray, filled by increasing length (palindromes, burst balloons).
  • State machine: dp[i][state] (stock problems: holding / not holding / cooldown).
LCS("abcde", "ace")            ""  a  c  e
                          ""    0  0  0  0
match -> diag + 1         a     0  1  1  1
else  -> max(up, left)    b     0  1  1  1
                          c     0  1  2  2
                          d     0  1  2  2
                          e     0  1  2  3   <- answer

Space trick: when a row only depends on the previous row, keep 1-D arrays.

Problems