HardNo. 0010

Regular Expression Matching — LeetCode 10 Python Solution

Topics
Recursion, String, Dynamic Programming
On a study list
NeetCode 150
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

PythonSolution
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

Time
O(m × n)
Space · auxiliary
O(m × n)

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

Related problems
No.ProblemDifficulty
0044Wildcard MatchingHard
0241Different Ways to Add ParenthesesMedium
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0072Edit DistanceMedium
0087Scramble StringHard

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 × n).

What is the space complexity of LeetCode 10. Regular Expression Matching?

The Python solution on this page uses O(m × 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.

Free to download. Check it runs on your machine, then pick a plan.