Skip to the page

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.

The 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

  1. Unique paths in an m x n grid.
  2. Longest common subsequence of two strings.
  3. Edit distance; where is it used in a product?
  4. Wildcard pattern matching with ? and *.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview