Regular Expression Matching (LeetCode 10): Solution and Explanation

Hard
String
Dynamic Programming
Recursion

Implement full-string matching for a pattern that supports ., which matches any one character, and *, which matches zero or more copies of the element right before it. The whole input string must be matched, not just a part of it.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without * this is trivial: walk both strings and compare character by character, treating . as a wildcard. The star is what makes it hard, because a* can consume zero, one or many characters and you cannot tell locally which choice is right. Trying all choices recursively works but can branch exponentially on patterns like a*a*a*b.

Those choices revisit the same pairs of positions, so cache them. Let dp[i][j] mean the first i characters of s match the first j characters of p. If p[j-1] is a plain letter or ., it must match s[i-1], and the rest reduces to dp[i-1][j-1]. If p[j-1] is *, treat x* as a unit with two options. Use it zero times, which means skipping both pattern characters: dp[i][j-2]. Or, if x matches s[i-1], let it absorb that character and stay on the same pattern position: dp[i-1][j].

The second option is what makes * repeatable without enumerating counts. Each time it eats one character it lands on a smaller subproblem that can choose again. The only special base case is the empty string, which can still be matched by patterns like a*b* where every starred element is used zero times.

Approach: 2D dynamic programming on prefixes

  1. Create an (m + 1) by (n + 1) table of False and set dp[0][0] = True.
  2. Fill row 0: for each j from 2, if p[j-1] is *, set dp[0][j] = dp[0][j-2] so patterns like a*b* match the empty string.
  3. For each i from 1 to m and j from 1 to n, check whether p[j-1] is *.
  4. If it is, set dp[i][j] to dp[i][j-2] (zero copies) or, when p[j-2] is . or equals s[i-1], to dp[i-1][j] (one more copy).
  5. Otherwise, if p[j-1] is . or equals s[i-1], set dp[i][j] = dp[i-1][j-1].
  6. Return dp[m][n].

Step-by-step example

s = "aab", p = "c*a*b"
  1. Row 0 (empty string) is [T, F, T, F, T, F]: c* and c*a* can both vanish, but c alone or anything ending in b cannot.
  2. Row 1 ("a"): column 3 (c*a) copies dp[0][2] = T. Column 4 (c*a*) is true because a matches the starred a and dp[0][4] is true.
  3. Row 2 ("aa"): column 4 is true again through dp[1][4], since the star absorbs the second a. Column 3 is false, as c*a cannot cover two letters.
  4. Row 3 ("aab"): column 5 compares b with b and copies dp[2][4] = T.
  5. dp[3][5] is true, so the pattern matches: c* takes nothing, a* takes aa, and b takes b.

Code: Python, Java, C++

1class Solution:
2    def isMatch(self, s: str, p: str) -> bool:
3        m, n = len(s), len(p)
4        dp = [[False] * (n + 1) for _ in range(m + 1)]
5        dp[0][0] = True
6
7        # Handle patterns like a*, a*b*, etc.
8        for j in range(2, n + 1):
9            if p[j - 1] == '*':
10                dp[0][j] = dp[0][j - 2]
11
12        for i in range(1, m + 1):
13            for j in range(1, n + 1):
14                if p[j - 1] == '*':
15                    # Zero occurrences OR one+ occurrences
16                    dp[i][j] = dp[i][j - 2] or (
17                        (p[j - 2] == '.' or p[j - 2] == s[i - 1]) and dp[i - 1][j]
18                    )
19                elif p[j - 1] == '.' or p[j - 1] == s[i - 1]:
20                    dp[i][j] = dp[i - 1][j - 1]
21
22        return dp[m][n]

Time and space complexity

Time

O(m × n)

Each of the (m + 1) × (n + 1) cells is computed once in constant time.

Space

O(m × n)

The full boolean table is stored. Two rows are enough if memory matters.

Other approaches

Plain recursion (time Exponential in the worst case, space O(m + n) recursion depth)

Match the first character, and on a * either skip the starred element or consume one character and recurse. It is short but exponential on adversarial patterns.

Top-down memoization (time O(m × n), space O(m × n))

The same recursion with a cache on (i, j) indices. It computes only the states that are actually reached and has the same worst case as the table.

Common mistakes

  • Forgetting to initialize row 0 for starred patterns. Without it, s = "" and p = "a*" returns false.
  • Treating * as matching any sequence, like a shell glob. Here it repeats only the single element right before it.
  • In the one-or-more branch, using dp[i-1][j-2] instead of dp[i-1][j]. Staying on column j is what allows the star to absorb more than one character.
  • Checking p[j-2] against s[i-1] without first confirming p[j-1] is *, which reads the wrong character and can index out of range.

Frequently asked questions

How does * work in regular expression matching?

It applies to the character just before it, so a* means zero or more as and .* means zero or more of any character. The DP handles it with two cases: skip the pair, or consume one matching character and stay on the pair.

What is the time complexity of regular expression matching?

O(m × n) with dynamic programming, where m and n are the lengths of the string and pattern. Naive recursion without memoization can be exponential.

Why is dp[0][j] true for some patterns?

An empty string can match a pattern if every element is followed by * and is used zero times, as in a*b*c*. Row 0 captures exactly those cases.

What is the difference from wildcard matching?

In wildcard matching, * matches any sequence by itself. Here * must follow an element and only repeats that element, which changes the recurrence.