Skip to content
Tech Interview Prep
Technical interview guide

2-D Dynamic Programming

DP where the subproblem needs two indices: grid paths, two-string comparisons, and knapsack-style capacity constraints.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with memoisation and recursion behaviour cited from CPython 3.14.

Overview

Curated: · Written: · Reviewed:

2-D Dynamic Programming

In one line

Use a second index when one index cannot capture what the answer depends on: a prefix of each of two sequences, a remaining budget or capacity, or a range. Reach for it when a one-dimensional state loses information the transition needs.

Key definitions

  • State: the subproblem a cell answers, written as one sentence before any code.
  • Prefix convention: dp[i][j] covers the first i characters of a and the first j of b, so the table is (m+1) x (n+1) and row 0 and column 0 are base cases.
  • Transition: the recurrence that combines predecessor cells. For 0/1 knapsack it is take-or-skip.
  • Rolling rows: keeping only the previous row when a row depends only on the one before it.
  • Hirschberg: linear-space alignment by divide and conquer over a forward and a backward pass.
  • Monotone split: an optimal split point that never moves backwards, which permits a narrowed search.

Formulas and complexity

LCS:dp[i][j]=dp[i−1][j−1]+1ifa[i−1]equalsb[j−1],elsemax(dp[i−1][j],dp[i][j−1]).TimeO(mn),spaceO(mn),O(min(m,n))withrollingrowsforthelengthonly.LCS: dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] equals b[j-1], else max(dp[i-1][j], dp[i][j-1]). Time O(mn), space O(mn), O(min(m,n)) with rolling rows for the length only. Editdistance:dp[i][0]=i,dp[0][j]=j,dp[i][j]=min(dp[i−1][j]+1,dp[i][j−1]+1,dp[i−1][j−1]+cost).TimeO(mn).Edit distance: dp[i][0] = i, dp[0][j] = j, dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost). Time O(mn). 0/1knapsack:dp[i][w]=max(dp[i−1][w],dp[i−1][w−wti]+vali)whenwti<=w.TimeO(nW).0/1 knapsack: dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt_i] + val_i) when wt_i <= w. Time O(nW). Matrixchain:dp[i][i]=0,dp[i][j]=minoveri<=k<jof(dp[i][k]+dp[k+1][j]+p[i−1]p[k]p[j]).TimeO(n3),spaceO(n2).Matrix chain: dp[i][i] = 0, dp[i][j] = min over i <= k < j of (dp[i][k] + dp[k+1][j] + p[i-1] p[k] p[j]). Time O(n^3), space O(n^2). Memory:10,000x10,000cellsx4bytes=400MB;tworollingrowsof10,001cells=about80KB.Memory: 10,000 x 10,000 cells x 4 bytes = 400 MB; two rolling rows of 10,001 cells = about 80 KB.

How it works

  1. Write the subproblem as a sentence. Its dimensions give the table, and the table gives the memory.
  2. Fill the base row and column with the operator's base values: prefix lengths for edit distance, 1s for grid counts, infinity for a minimum.
  3. Each cell combines its predecessors. A match extends the diagonal; otherwise the cell takes the better neighbour.
  4. Fill in dependency order: row by row for prefixes, by increasing length for ranges. Collapsed 0/1 knapsack iterates capacity downward.
  5. Read the answer at the cell the sentence names, usually the bottom-right. Reconstruct by walking back from it.
match: plus 1 skip a char skip b char dp i-1 j-1 dp i j dp i-1 j dp i j-1

When to use and when not to

SituationUse 2-D DPPrefer instead
Two sequences, alignment or scoreYes, O(mn)Nothing cheaper in general
Budget with exact weights, small capacityYes, index by remaining capacityIndex by value when weights are huge: dp[v] = minimum weight reaching value v
Only the longest palindromeNoExpand around centres: O(n^2) time, O(1) space
Few reachable states in a large spaceDict memoDense table wastes memory
Alignment needed, memory tightHirschbergFull table exceeds the budget

Traps interviewers probe

  1. Zero as the base of a minimum. Zero is the identity for addition, so every cell comes out zero. Fix: initialise with infinity and set dp[0][0] to the entry cost.
  2. Blocked border cells. Skipping only the obstacle leaves later border cells reachable. Fix: break the border loop at the first obstacle.
  3. Upward capacity loop after collapsing. Items get reused and 4 + 4 = 8 passes for items {4, 6}. Fix: iterate capacity downward for 0/1, or read the previous row in the two-row version.
  4. Wrong answer cell. Returning dp[m-1][n-1] for LCS('ABC', 'AC') gives 1 instead of 2. Fix: return dp[m][n] under the prefix convention.
  5. Wrong order for ranges. Iterating by left endpoint reads uncomputed sub-ranges. A palindrome loop that ascends i reads row i+1 before it is filled and reports 8 instead of 9 for 'aabaa'. Fix: loop by length, or descend i.

Interview tips

Open by naming the subproblem: 'dp[i][j] is the best value over the first i of a and the first j of b.' Then state the recurrence, base cases, fill order, answer cell, and complexity.

Follow-ups to expect:

  • Can you cut the memory? Rolling rows keep the value but discard the alignment. Hirschberg keeps the alignment in linear space.
  • Why is top-down risky here? Depth grows with m + n. CPython's default limit of 1,000 raises RecursionError for 4,000 x 6,000.
  • Does weighted edit distance stay symmetric? Not with asymmetric costs, so cache by the ordered pair, not frozenset.
  • Can you use the monotone optimisation? Only after verifying the split point is monotone, then testing against the plain DP.
  • Are the reconstructed sequences unique? Not under ties. Assert the value and the validity of the output.

30-second outline: 'dp[i][j] is the best result over the first i of a and the first j of b. It takes the diagonal on a match and the better neighbour otherwise. Base cases are the prefix lengths. I fill row by row and read dp[m][n]. Time and space are O(mn). If only the value is needed, two rows bring space to O(n). If the alignment is needed, I keep the table or use Hirschberg.'

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.