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
- dp[0][0] = true; dp[0][j] is true for patterns like
a*b*that can be empty. - If
p[j-1]is a letter or ., match the last characters and read the diagonal. - If
p[j-1]is *, either use zero copies (dp[i][j-2]) or, if the preceding element matchess[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.