15% off all plans & roadmaps Use code

See plans

Regular Expression Matching

Updated

TL;DR: Decide whether a pattern with `.` and `*` matches an entire string. Treat each pair (position in s, position in p) as one state and fill a DP table, because the same pairs repeat in plain recursion.

Problem

Implement isMatch to decide whether the whole string s is described by the pattern p. Return true only when the pattern consumes every character of s. Otherwise return false.

The pattern contains lowercase letters, . and *. A lowercase letter matches itself, and . matches any single lowercase character. The symbol * applies to the element right before it and lets that element appear zero or more times.

Matching covers all of s, not just a prefix. Every * in p follows a valid element, so the pattern is always well formed.

Example 1

Input: s = "candle", p = "c.nd.*"
Output: true
Explanation: The dot matches a, and .* matches the remaining le, so the whole string is covered.

Example 2

Input: s = "abz", p = "a.*c"
Output: false
Explanation: .* can match b, but the final c cannot match the final character z.

Example 3

Input: s = "", p = "q*"
Output: true
Explanation: q* may occur zero times, which matches the empty string.

Constraints

  • 0 <= s.length <= 20
  • 0 <= p.length <= 20
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, . and *.
  • Every * in p is preceded by a valid character or ..
  • The match must consume all of s.

Constraints that matter

  • s and p have at most 20 characters each, so an O(n * m) table has at most 441 cells. Exponential recursion still risks blowing up on patterns like a*a*a*a*b against a long run of a.
  • Every * follows a valid element, so p[j - 2] always exists when p[j - 1] is *. You never need to guard against a leading star.
  • Both strings can be empty. The table needs a row and a column for the empty prefix, and the first row must be filled using the zero-occurrence rule.
  • The match must consume all of s. Your base case has to require that the string and the pattern end together.
  • Only lowercase letters appear, so . never has to match a special character. Comparing characters directly is safe.

View on LeetCode

Hints

Hint 1

This is a two-string DP problem.

Hint 2

Write a function match(i, j) that answers whether s[i:] matches p[j:].

Solution

Intuition

This is a two-string DP problem. At any moment the only things that matter are how much of s you have used and how much of p you have used. Two integers (i, j) describe that moment completely. The answer for the rest of the match depends on nothing else.

Picture a grid of sticky notes, one per (i, j) pair, where each note is written only after the notes it depends on. The sticky note in row i, column j is the saved answer for that state, so nothing is solved twice.

That is the signal for dynamic programming. A plain recursive solution reaches the same (i, j) pair through many different routes, especially when several * elements can each eat a different number of characters. If you solve each pair once, the work drops from exponential to n * m.

The hard part is *. A starred element x* has exactly two possible behaviours at a given spot. It occurs zero times, so you skip x* and move two steps along the pattern. Or it occurs at least once, so x must match the current character, and you consume that character while staying on x* for another round.

Every other element is rigid. A letter or a dot must match exactly one character, and both positions move forward by one. Add the rule that both strings must end together, and the whole problem is those three transitions.

Watch the pattern animation

Worked example

Input: s = "candle", p = "c.nd.*"
Output: true
Explanation: c matches c, . matches a, n matches n, and d matches d. The last element .* then absorbs the leftover le, so both strings end together.

Approach 1: Brute force recursion

Write a function match(i, j) that answers whether s[i:] matches p[j:]. Try every legal interpretation of each * and return true if any path reaches the end of both strings.

There is no caching here. This is the version a beginner writes straight from the definition of the problem.

Steps

  1. If j has reached the end of p, return whether i has reached the end of s.
  2. Compute first: i is inside s and p[j] is . or equals s[i].
  3. If p[j + 1] is *, return match(i, j + 2) or (first and match(i + 1, j)).
  4. Otherwise return first and match(i + 1, j + 1).
  5. Start with match(0, 0).

Dry run

Trace s = candle, p = c.nd.* with 0-based indices.

  • match(0,0): c equals c, go to match(1,1).
  • match(1,1): . matches a, go to match(2,2).
  • match(2,2) and match(3,3): n and d match, reach match(4,4).
  • match(4,4): .* is starred. Skip it with match(4,6): pattern is over but i = 4 < 6, so false.
  • Consume one character: match(5,4). Skip gives match(5,6), false. Consume gives match(6,4).
  • match(6,4): skip gives match(6,6): both ended, true.

The result is true.

Complexity

TimeO(2^(n + m))
SpaceO(n + m)

Let n = len(s) and m = len(p). Every call either moves i forward by one, moves j forward by at least one, or both, so the recursion depth is at most n + m. Each call branches into at most two children, so the call tree has at most about 2^(n + m) nodes, which is an upper bound and not always reached. The only extra memory is the call stack, which is O(n + m).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        n, m = len(s), len(p)

        def match(i: int, j: int) -> bool:
            if j == m:
                return i == n
            first = i < n and (p[j] == '.' or p[j] == s[i])
            if j + 1 < m and p[j + 1] == '*':
                # zero occurrences, or one more occurrence
                return match(i, j + 2) or (first and match(i + 1, j))
            return first and match(i + 1, j + 1)

        return match(0, 0)

Approach 2: Top-down memoization

What's slow: the recursion answers the same (i, j) question again and again. With a pattern like a*a*a*b, many different split choices land on identical positions, and each landing re-explores everything behind it.

The insight that fixes it: match(i, j) depends only on i and j, so its answer never changes. Store each answer in a table of size (n + 1) by (m + 1) the first time you compute it. Every later call is a lookup.

Steps

  1. Create a table memo with n + 1 rows and m + 1 columns, all marked unknown.
  2. In match(i, j), return the stored value if the cell is known.
  3. Otherwise compute the result with the same rules as the brute force version.
  4. Store the result in memo[i][j] before returning it.
  5. Return match(0, 0).

Dry run

On candle and c.nd.* the calls form a single chain, so the table fills in order.

  • memo[0][0] needs memo[1][1], which needs memo[2][2], then memo[3][3], then memo[4][4].
  • memo[4][4] calls memo[4][6]: false, stored.
  • It then calls memo[5][4], which calls memo[5][6]: false, stored.
  • memo[5][4] calls memo[6][4], which calls memo[6][6]: true, stored.
  • Results flow back: memo[6][4] true, memo[5][4] true, memo[4][4] true, and so on to memo[0][0] true.

This input never repeats a state, but the table guarantees it on inputs that would. The result is true.

Complexity

TimeO(n * m)
SpaceO(n * m)

Let n = len(s) and m = len(p). There are (n + 1) * (m + 1) distinct states, and each one is computed once. Computing a state does constant work beyond its two or three recursive lookups. The table holds n * m entries, and the recursion depth adds only O(n + m).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        n, m = len(s), len(p)
        memo = [[None] * (m + 1) for _ in range(n + 1)]

        def match(i: int, j: int) -> bool:
            if memo[i][j] is not None:
                return memo[i][j]
            if j == m:
                res = i == n
            else:
                first = i < n and (p[j] == '.' or p[j] == s[i])
                if j + 1 < m and p[j + 1] == '*':
                    res = match(i, j + 2) or (first and match(i + 1, j))
                else:
                    res = first and match(i + 1, j + 1)
            memo[i][j] = res
            return res

        return match(0, 0)
2D Array (Edit Distance / Levenshtein Distance) pattern infographic for Regular Expression Matching

Solution pattern

2D Array (Edit Distance / Levenshtein Distance)

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up DP tableOptimal2D Array (Edit Distance / Levenshtein Distance)

What's slow: memoization is already O(n * m), but it pays for a recursive call, a cache check and a stack frame on every state. It also asks you to reason about call order.

The insight that fixes it: define dp[i][j] as true when the first i characters of s match the first j characters of p. Every cell depends only on cells with a smaller i or j. Fill the table row by row, and the answer waits in dp[n][m].

Why it is correct. The invariant is that dp[i][j] is true exactly when the first i characters of s match the first j elements of p. Each transition covers every way the last pattern element can match, so no valid match is lost. A star either occurs zero times or at least once, so the case split is exhaustive.

Steps

  1. Create dp with n + 1 rows and m + 1 columns, all false, and set dp[0][0] to true.
  2. Fill row 0: for each j from 2 to m, if p[j - 1] is *, set dp[0][j] = dp[0][j - 2]. This lets a*b* match the empty string.
  3. For each i from 1 to n and j from 1 to m, look at p[j - 1].
  4. If it is *, start with dp[i][j] = dp[i][j - 2] for zero occurrences.
  5. Still in the star case, if p[j - 2] is . or equals s[i - 1], also allow dp[i - 1][j], which uses one more occurrence.
  6. If it is a letter or . that matches s[i - 1], set dp[i][j] = dp[i - 1][j - 1].
  7. Return dp[n][m].

Dry run

Use s = candle (rows 1 to 6 are c, a, n, d, l, e) and p = c.nd.* (columns 1 to 6 are c, ., n, d, ., *). Row 0 has only dp[0][0] true, since p[3] is d, which blocks dp[0][6] = dp[0][4].

Row i (char)Cell computedRule usedValue
1 (c)dp[1][1]c equals c, take dp[0][0]true
1 (c)dp[1][2]. matches, take dp[0][1]false
1 (c)dp[1][6]skip dp[1][4] is false, extend dp[0][6] is falsefalse
2 (a)dp[2][2]. matches a, take dp[1][1]true
3 (n)dp[3][3]n equals n, take dp[2][2]true
4 (d)dp[4][4]d equals d, take dp[3][3]true
4 (d)dp[4][5]. matches, take dp[3][4]false
4 (d)dp[4][6]skip: dp[4][4]true
5 (l)dp[5][5]. matches l, take dp[4][4]true
5 (l)dp[5][6]skip dp[5][4] false, extend dp[4][6]true
6 (e)dp[6][5]. matches e, take dp[5][4]false
6 (e)dp[6][6]skip dp[6][4] false, extend dp[5][6]true

All other cells are false. dp[6][6] is true, so the answer is true.

Complexity

TimeO(n * m)
SpaceO(n * m)

Let n = len(s) and m = len(p). The table has (n + 1) * (m + 1) cells, and the two nested loops visit each cell once. Each cell reads at most three earlier cells, so the work per cell is constant. The table itself is the only structure that grows, which gives O(n * m) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        n, m = len(s), len(p)
        # dp[i][j]: first i chars of s match first j chars of p
        dp = [[False] * (m + 1) for _ in range(n + 1)]
        dp[0][0] = True

        # empty string can match patterns like a*b*
        for j in range(2, m + 1):
            if p[j - 1] == '*':
                dp[0][j] = dp[0][j - 2]

        for i in range(1, n + 1):
            for j in range(1, m + 1):
                if p[j - 1] == '*':
                    # zero occurrences of the starred element
                    dp[i][j] = dp[i][j - 2]
                    # one more occurrence if the element matches s[i - 1]
                    if p[j - 2] == '.' or p[j - 2] == s[i - 1]:
                        dp[i][j] = dp[i][j] or dp[i - 1][j]
                elif p[j - 1] == '.' or p[j - 1] == s[i - 1]:
                    dp[i][j] = dp[i - 1][j - 1]

        return dp[n][m]

Common mistakes

  • Treating * as a wildcard for any string, so a* matches abc. In this problem * repeats the element before it, so you must test p[j - 2] against s[i - 1] before extending.
  • Dropping the zero-occurrence branch (dp[i][j - 2] or match(i, j + 2)). Then q* can never match the empty string and a*b can never match b. Always compute the skip option first.
  • Moving both indices after one star match, as in match(i + 1, j + 1). That allows only one repetition, so aaa against a* fails. Stay on the star with match(i + 1, j) or dp[i - 1][j].
  • Reading s[i] without checking i < n. The first flag must start with i < n and ..., because . cannot match the empty remainder and an out-of-range read crashes in Java, C# and Go.
  • Returning true when j == m without comparing i == n. That accepts prefix matches, so ab against a wrongly passes. The base case must be i == n.
  • Off by one when checking for star in a prefix table: using p[j] instead of p[j - 1], or p[j - 1] instead of p[j - 2] for the starred element. Row and column k of the table refer to character k - 1, so shift every index by one.

Edge cases

  • s = "", p = "": both empty, returns true because dp[0][0] is true.
  • s = "", p = "a*b*c*": every starred group takes zero occurrences, returns true.
  • s = "a", p = "": pattern ends with characters left in s, returns false.
  • s = "aaa", p = "a*a": the star must give back one a for the last literal, returns true.
  • s = "ab", p = ".*": dot-star matches any string of lowercase letters, returns true.
  • s = "aab", p = "c*a*b": c* takes zero occurrences, a* takes two, returns true.

Follow-ups interviewers ask

Can you reduce the space below O(n * m)?
Yes. Row i of the prefix table reads only row i - 1 and earlier cells of row i. Keep two rows, or one row updated carefully, and space drops to O(m). Time stays O(n * m).
How does this change for wildcard matching, where * matches any sequence?
The state is the same, but the star transition changes. A * matches any run of characters, so dp[i][j] is true if dp[i][j - 1] (empty run) or dp[i - 1][j] (extend the run) is true. There is no preceding element to check, and the table is still n * m.
Could you match without building a table, in less time?
You can convert the pattern into an automaton and simulate it, tracking the set of active states. With a Thompson-style NFA, matching takes O(n * m) time and O(m) space, which is the same time bound but a lower space bound. For these constraints the table is simpler to write and explain.

Regular Expression Matching FAQ

What is the time complexity of Regular Expression Matching?

The DP and memoized solutions run in O(n * m) time and O(n * m) space, where n is len(s) and m is len(p). The plain recursion is exponential, bounded by about 2^(n + m). The table has (n + 1) * (m + 1) cells and each is computed once in constant time.

Why use dynamic programming for Regular Expression Matching?

The answer for the rest of the match depends only on the pair (characters of s used, characters of p used). Different star choices reach the same pair by different routes, so plain recursion repeats work. A DP table or memo solves each pair once, which cuts exponential time to n * m.

How do I solve LeetCode 10 in Python?

Build a boolean table dp of size (n + 1) by (m + 1) with dp[0][0] = True. Fill the first row using the zero-occurrence rule for stars, then fill each cell by the star, dot-or-letter, and mismatch rules. Return dp[n][m]. The bottom-up code on this page is that solution.

Can Regular Expression Matching be solved in O(1) extra space?

Not with a general DP. The table needs at least one row, which is O(m) space, or O(min(n, m)) if you pick the shorter string for the row. A greedy two-pointer scan with backtracking works for wildcard matching but fails here, because a starred element tied to a specific letter cannot be resolved by one backtrack point.

What is the difference between `.*` and `*` in this problem?

* never stands alone. It repeats the single element before it. .* repeats a dot, so it matches any sequence of lowercase letters, including the empty one. The pattern * by itself is not valid input.

Can I use Python's re module to solve it?

For these inputs re.fullmatch(p, s) agrees with the problem rules, so it would likely return the right answers. Interviewers expect you to implement the matching yourself, so use the DP and treat re only as a way to check your output.

Asked at

See which companies ask this — Pro

Practise it