Dynamic programming · senior
Two-dimensional DP on strings and grids
When the state needs two indices (a cell row and column, or a position in each of two strings), dp[i][j] is filled from its top, left and diagonal neighbours, which solves grid paths, longest common subsequence, edit distance and wildcard matching.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Grid paths: dp[r][c] = dp[r - 1][c] + dp[r][c - 1]; only one row of memory is needed.
- LCS: if a[i - 1] == b[j - 1] then dp[i][j] = dp[i - 1][j - 1] + 1, else max(dp[i - 1][j], dp[i][j - 1]).
- Edit distance: min(insert dp[i][j - 1], delete dp[i - 1][j], replace dp[i - 1][j - 1]) + 1, or the diagonal value for free when the characters match. Used by diff tools and 'did you mean'.
- Wildcard (? and ): '' means dp[i][j - 1] (matches empty) or dp[i - 1][j] (takes one more character). Base: an empty pattern matches only empty text; leading stars match empty text.
- Word break: dp[i] is true if some j < i has dp[j] true and the substring from j to i is in the dictionary set; limit j by the longest word.
- Size the table (n + 1) x (m + 1) so that row 0 and column 0 mean 'empty prefix'; this removes most off-by-one bugs.
The red pen
Common traps: mistake → fix
Mistake: Use an n x m table
Fix: without the empty row and column the base cases get messy.
Mistake: Wildcard and regex '*' are the same
Fix: regex '' repeats the previous character; wildcard '' matches any sequence.
Mistake: Greedy word break (longest prefix first)
Fix: fails on some dictionaries; use DP.
Easy to hard
Questions interviewers ask, easy to hard
- Unique paths in an m x n grid.
- Longest common subsequence of two strings.
- Edit distance; where is it used in a product?
- Wildcard pattern matching with ? and *.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.