Dynamic programming · senior
Two-dimensional DP in JavaScript (strings and grids)
When the state needs two indices (a cell, or a position in each of two strings), dp[i][j] is filled from its top, left and diagonal neighbours: grid paths, longest common subsequence, edit distance and wildcard matching. In JavaScript, build the table with Array.from so rows are not shared, and keep only two rows when memory matters.
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(top, left).
- Edit distance: min(insert dp[i][j − 1], delete dp[i − 1][j], replace dp[i − 1][j − 1]) + 1, or the diagonal for free when characters match. Used by diff tools and 'did you mean'.
- Wildcard (? and ): '' → dp[i][j − 1] (matches empty) or dp[i − 1][j] (eats one char). Base: empty pattern matches only empty text; leading stars match empty.
- Word break: dp[i] true if some j < i has dp[j] and s.slice(j, i) in a Set; limit j by the longest word.
- Size the table (n + 1) × (m + 1) so row 0 / column 0 mean 'empty prefix'; this removes most off-by-one bugs.
- Build the table with Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0)). new Array(n + 1).fill(new Array(m + 1).fill(0)) shares one row, so writing dp[1][2] also changes dp[0][2].
The red pen
Common traps: mistake → fix
Mistake: Use an n × 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.
Mistake: new Array(n).fill(new Array(m).fill(0)) makes a grid
Fix: all rows are the same array.
Easy to hard
Questions interviewers ask, easy to hard
- Unique paths in an m × n grid.
- Longest common subsequence of two strings.
- Edit distance; where is it used in a frontend 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.