Regular Expression Matching — LeetCode 10 Python Solution

HardRecursionStringDynamic Programming
Problem
#10
Reading time
3 min

The problem

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).

Example

Input
s = "aa", p = "a"
Output
false
Explanation
"a" does not match the entire string "aa".

Python solution

Python
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        @cache
        def dfs(i, j):
            if j >= n:
                return i == m
            if j + 1 < n and p[j + 1] == '*':
                return dfs(i, j + 2) or (
                    i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j)
                )
            return i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1)

        m, n = len(s), len(p)
        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 10. Regular Expression Matching is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 10. Regular Expression Matching?
LeetCode 10. Regular Expression Matching is rated Hard on LeetCode.
What is the time complexity of LeetCode 10. Regular Expression Matching?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 10. Regular Expression Matching?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 10. Regular Expression Matching cover?
LeetCode 10. Regular Expression Matching is tagged Recursion, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview