Pattern

2D dynamic programming

A DP whose state is a pair of positions — usually two prefix lengths — so the table and its dependencies are genuinely two-dimensional.

What it is

A 2D dynamic program indexes its state by a pair of numbers rather than one, most often "how much of sequence A have I consumed" crossed with "how much of sequence B have I consumed," or "row" crossed with "column" on an actual grid. The table is conceptually rows × cols, and each cell's value comes from a small fixed set of already-computed neighbors — directly above, directly to the left, or diagonally up-left. The two-dimensional shape is what you get whenever a problem compares or merges two sequences, or asks about a literal 2D structure like a matrix.

When it applies

Tells in the problem

The classic mistake

A common shape for this bug is a state tuple with a redundant third dimension — for example, separately tracking "position in the merged output" alongside (i, j) when consuming from two sources, forgetting that the merged position is always i + j and adds nothing. The result is a needlessly 3D table, extra bugs in keeping the dimensions in sync, and a much harder correctness argument. A second common mistake is filling the table in the wrong order so a cell's dependency (usually above-left) hasn't been computed yet, especially when the DP is space-optimized down to one rolling row — overwriting dp[j-1] before reading its old value as the "diagonal" input is the specific bug to watch for. Before compressing to O(n) space, write out on paper exactly which of the row's old and new values each transition needs.

Questions to start with

All 8 2d dynamic programming questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.