TRT
Sign in
hardAdvancedLeetCode#two-string DP#star handling

Regular expression matching

Match a string against a pattern with . and * using a table over string and pattern prefixes.

The Runtime Theory Team1 min read
Taught inGrids and stringsPro — members onlyTwo-dimensional DP fills a table whose cells depend on their neighbors above and to the left. On grids it counts or optimizes paths; on two strings, a cell compares two prefixes, which is how diff tools, spell checkers and DNA alignment work.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = aa, p = a

outfalse

ins = aa, p = a*

outtrue

ins = ab, p = .*

outtrue

Implement matching where . matches any single character and * matches zero or more of the preceding element. The whole string must match.

Before you code

dp[i][j] says whether the first i characters of s match the first j of p. A star pairs with the element before it, so it reads two pattern positions back.

Hints

  1. dp[0][0] = true; dp[0][j] is true for patterns like a*b* that can be empty.
  2. If p[j-1] is a letter or ., match the last characters and read the diagonal.
  3. If p[j-1] is *, either use zero copies (dp[i][j-2]) or, if the preceding element matches s[i-1], one more copy (dp[i-1][j]).

Production & complexity notes

When solving Regular expression matching on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Grids and strings to reinforce the underlying pattern.

What it practices

Reading a recurrence off the last pattern element, from Grids and strings.

Not started

Sign in to save your learning progress.

Sign in to save