15% off all plans & roadmaps Use code
See plansRegular 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 <= 200 <= p.length <= 20scontains only lowercase English letters.pcontains only lowercase English letters,.and*.- Every
*inpis preceded by a valid character or.. - The match must consume all of
s.
Constraints that matter
sandphave at most 20 characters each, so an O(n * m) table has at most 441 cells. Exponential recursion still risks blowing up on patterns likea*a*a*a*bagainst a long run ofa.- Every
*follows a valid element, sop[j - 2]always exists whenp[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.
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.
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
- If
jhas reached the end ofp, return whetherihas reached the end ofs. - Compute
first:iis insidesandp[j]is.or equalss[i]. - If
p[j + 1]is*, returnmatch(i, j + 2)or (firstandmatch(i + 1, j)). - Otherwise return
firstandmatch(i + 1, j + 1). - Start with
match(0, 0).
Dry run
Trace s = candle, p = c.nd.* with 0-based indices.
match(0,0):cequalsc, go tomatch(1,1).match(1,1):.matchesa, go tomatch(2,2).match(2,2)andmatch(3,3):nanddmatch, reachmatch(4,4).match(4,4):.*is starred. Skip it withmatch(4,6): pattern is over buti = 4 < 6, so false.- Consume one character:
match(5,4). Skip givesmatch(5,6), false. Consume givesmatch(6,4). match(6,4): skip givesmatch(6,6): both ended, true.
The result is true.
Complexity
| Time | O(2^(n + m)) |
|---|---|
| Space | O(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)
JavaTested in our runner
import java.util.*;
class Solution {
public boolean isMatch(String s, String p) {
return match(s, p, 0, 0);
}
private boolean match(String s, String p, int i, int j) {
if (j == p.length()) {
return i == s.length();
}
boolean first = i < s.length() && (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i));
if (j + 1 < p.length() && p.charAt(j + 1) == '*') {
return match(s, p, i, j + 2) || (first && match(s, p, i + 1, j));
}
return first && match(s, p, i + 1, j + 1);
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
return match(s, p, 0, 0);
}
private:
bool match(const string& s, const string& p, int i, int j) {
int n = s.size(), m = p.size();
if (j == m) return i == n;
bool first = i < n && (p[j] == '.' || p[j] == s[i]);
if (j + 1 < m && p[j + 1] == '*') {
return match(s, p, i, j + 2) || (first && match(s, p, i + 1, j));
}
return first && match(s, p, i + 1, j + 1);
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
const n = s.length, m = p.length;
const match = (i, j) => {
if (j === m) return i === n;
const first = i < n && (p[j] === '.' || p[j] === s[i]);
if (j + 1 < m && p[j + 1] === '*') {
return match(i, j + 2) || (first && match(i + 1, j));
}
return first && match(i + 1, j + 1);
};
return match(0, 0);
};
GoTested in our runner
func isMatch(s string, p string) bool {
n, m := len(s), len(p)
var match func(i, j int) bool
match = func(i, j int) bool {
if j == m {
return i == n
}
first := i < n && (p[j] == '.' || p[j] == s[i])
if j+1 < m && p[j+1] == '*' {
return match(i, j+2) || (first && match(i+1, j))
}
return first && match(i+1, j+1)
}
return match(0, 0)
}
C#Tested in our runner
public class Solution {
public bool isMatch(string s, string p) {
return Match(s, p, 0, 0);
}
private bool Match(string s, string p, int i, int j) {
if (j == p.Length) {
return i == s.Length;
}
bool first = i < s.Length && (p[j] == '.' || p[j] == s[i]);
if (j + 1 < p.Length && p[j + 1] == '*') {
return Match(s, p, i, j + 2) || (first && Match(s, p, i + 1, j));
}
return first && Match(s, p, i + 1, j + 1);
}
}
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
- Create a table
memowith n + 1 rows and m + 1 columns, all marked unknown. - In
match(i, j), return the stored value if the cell is known. - Otherwise compute the result with the same rules as the brute force version.
- Store the result in
memo[i][j]before returning it. - 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]needsmemo[1][1], which needsmemo[2][2], thenmemo[3][3], thenmemo[4][4].memo[4][4]callsmemo[4][6]: false, stored.- It then calls
memo[5][4], which callsmemo[5][6]: false, stored. memo[5][4]callsmemo[6][4], which callsmemo[6][6]: true, stored.- Results flow back:
memo[6][4]true,memo[5][4]true,memo[4][4]true, and so on tomemo[0][0]true.
This input never repeats a state, but the table guarantees it on inputs that would. The result is true.
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(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)
JavaTested in our runner
import java.util.*;
class Solution {
public boolean isMatch(String s, String p) {
Boolean[][] memo = new Boolean[s.length() + 1][p.length() + 1];
return match(s, p, 0, 0, memo);
}
private boolean match(String s, String p, int i, int j, Boolean[][] memo) {
if (memo[i][j] != null) {
return memo[i][j];
}
boolean res;
if (j == p.length()) {
res = i == s.length();
} else {
boolean first = i < s.length() && (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i));
if (j + 1 < p.length() && p.charAt(j + 1) == '*') {
res = match(s, p, i, j + 2, memo) || (first && match(s, p, i + 1, j, memo));
} else {
res = first && match(s, p, i + 1, j + 1, memo);
}
}
memo[i][j] = res;
return res;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<int>> memo(s.size() + 1, vector<int>(p.size() + 1, -1));
return match(s, p, 0, 0, memo);
}
private:
bool match(const string& s, const string& p, int i, int j, vector<vector<int>>& memo) {
if (memo[i][j] != -1) return memo[i][j] == 1;
int n = s.size(), m = p.size();
bool res;
if (j == m) {
res = i == n;
} else {
bool first = i < n && (p[j] == '.' || p[j] == s[i]);
if (j + 1 < m && p[j + 1] == '*') {
res = match(s, p, i, j + 2, memo) || (first && match(s, p, i + 1, j, memo));
} else {
res = first && match(s, p, i + 1, j + 1, memo);
}
}
memo[i][j] = res ? 1 : 0;
return res;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
const n = s.length, m = p.length;
// -1 unknown, 0 false, 1 true
const memo = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(-1));
const match = (i, j) => {
if (memo[i][j] !== -1) return memo[i][j] === 1;
let res;
if (j === m) {
res = i === n;
} else {
const first = i < n && (p[j] === '.' || p[j] === s[i]);
if (j + 1 < m && p[j + 1] === '*') {
res = match(i, j + 2) || (first && match(i + 1, j));
} else {
res = first && match(i + 1, j + 1);
}
}
memo[i][j] = res ? 1 : 0;
return res;
};
return match(0, 0);
};
GoTested in our runner
func isMatch(s string, p string) bool {
n, m := len(s), len(p)
// 0 unknown, 1 true, 2 false
memo := make([][]int8, n+1)
for i := range memo {
memo[i] = make([]int8, m+1)
}
var match func(i, j int) bool
match = func(i, j int) bool {
if memo[i][j] != 0 {
return memo[i][j] == 1
}
var res bool
if j == m {
res = i == n
} else {
first := i < n && (p[j] == '.' || p[j] == s[i])
if j+1 < m && p[j+1] == '*' {
res = match(i, j+2) || (first && match(i+1, j))
} else {
res = first && match(i+1, j+1)
}
}
if res {
memo[i][j] = 1
} else {
memo[i][j] = 2
}
return res
}
return match(0, 0)
}
C#Tested in our runner
public class Solution {
public bool isMatch(string s, string p) {
// 0 unknown, 1 true, 2 false
int[,] memo = new int[s.Length + 1, p.Length + 1];
return Match(s, p, 0, 0, memo);
}
private bool Match(string s, string p, int i, int j, int[,] memo) {
if (memo[i, j] != 0) {
return memo[i, j] == 1;
}
bool res;
if (j == p.Length) {
res = i == s.Length;
} else {
bool first = i < s.Length && (p[j] == '.' || p[j] == s[i]);
if (j + 1 < p.Length && p[j + 1] == '*') {
res = Match(s, p, i, j + 2, memo) || (first && Match(s, p, i + 1, j, memo));
} else {
res = first && Match(s, p, i + 1, j + 1, memo);
}
}
memo[i, j] = res ? 1 : 2;
return res;
}
}

Solution pattern
2D Array (Edit Distance / Levenshtein Distance)
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
- Create
dpwith n + 1 rows and m + 1 columns, all false, and setdp[0][0]to true. - Fill row 0: for each
jfrom 2 to m, ifp[j - 1]is*, setdp[0][j] = dp[0][j - 2]. This letsa*b*match the empty string. - For each
ifrom 1 to n andjfrom 1 to m, look atp[j - 1]. - If it is
*, start withdp[i][j] = dp[i][j - 2]for zero occurrences. - Still in the star case, if
p[j - 2]is.or equalss[i - 1], also allowdp[i - 1][j], which uses one more occurrence. - If it is a letter or
.that matchess[i - 1], setdp[i][j] = dp[i - 1][j - 1]. - 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 computed | Rule used | Value |
|---|---|---|---|
| 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 false | false |
| 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
| Time | O(n * m) |
|---|---|
| Space | O(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]
JavaTested in our runner
import java.util.*;
class Solution {
public boolean isMatch(String s, String p) {
int n = s.length(), m = p.length();
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for (int j = 2; j <= m; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 2];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') {
dp[i][j] = dp[i][j - 2];
char prev = p.charAt(j - 2);
if (prev == '.' || prev == s.charAt(i - 1)) {
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
} else if (pc == '.' || pc == s.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
int n = s.size(), m = p.size();
vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, false));
dp[0][0] = true;
for (int j = 2; j <= m; ++j) {
if (p[j - 1] == '*') {
dp[0][j] = dp[0][j - 2];
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (p[j - 1] == '*') {
bool res = dp[i][j - 2];
char prev = p[j - 2];
if (prev == '.' || prev == s[i - 1]) {
res = res || dp[i - 1][j];
}
dp[i][j] = res;
} else if (p[j - 1] == '.' || p[j - 1] == s[i - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
const n = s.length, m = p.length;
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(false));
dp[0][0] = true;
for (let j = 2; j <= m; j++) {
if (p[j - 1] === '*') dp[0][j] = dp[0][j - 2];
}
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (p[j - 1] === '*') {
dp[i][j] = dp[i][j - 2];
if (p[j - 2] === '.' || p[j - 2] === s[i - 1]) {
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
} else if (p[j - 1] === '.' || p[j - 1] === s[i - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[n][m];
};
GoTested in our runner
func isMatch(s string, p string) bool {
n, m := len(s), len(p)
dp := make([][]bool, n+1)
for i := range dp {
dp[i] = make([]bool, m+1)
}
dp[0][0] = true
for j := 2; j <= m; j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-2]
}
}
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
if p[j-1] == '*' {
dp[i][j] = dp[i][j-2]
if p[j-2] == '.' || p[j-2] == s[i-1] {
dp[i][j] = dp[i][j] || dp[i-1][j]
}
} else if p[j-1] == '.' || p[j-1] == s[i-1] {
dp[i][j] = dp[i-1][j-1]
}
}
}
return dp[n][m]
}
C#Tested in our runner
public class Solution {
public bool isMatch(string s, string p) {
int n = s.Length, m = p.Length;
bool[,] dp = new bool[n + 1, m + 1];
dp[0, 0] = true;
for (int j = 2; j <= m; j++) {
if (p[j - 1] == '*') {
dp[0, j] = dp[0, j - 2];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (p[j - 1] == '*') {
dp[i, j] = dp[i, j - 2];
if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) {
dp[i, j] = dp[i, j] || dp[i - 1, j];
}
} else if (p[j - 1] == '.' || 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, soa*matchesabc. In this problem*repeats the element before it, so you must testp[j - 2]againsts[i - 1]before extending. - Dropping the zero-occurrence branch (
dp[i][j - 2]ormatch(i, j + 2)). Thenq*can never match the empty string anda*bcan never matchb. 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, soaaaagainsta*fails. Stay on the star withmatch(i + 1, j)ordp[i - 1][j]. - Reading
s[i]without checkingi < n. Thefirstflag must start withi < n and ..., because.cannot match the empty remainder and an out-of-range read crashes in Java, C# and Go. - Returning true when
j == mwithout comparingi == n. That accepts prefix matches, soabagainstawrongly passes. The base case must bei == n. - Off by one when checking for star in a prefix table: using
p[j]instead ofp[j - 1], orp[j - 1]instead ofp[j - 2]for the starred element. Row and columnkof the table refer to characterk - 1, so shift every index by one.
Edge cases
s = "",p = "": both empty, returns true becausedp[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 ins, returns false.s = "aaa",p = "a*a": the star must give back oneafor 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
iof the prefix table reads only rowi - 1and earlier cells of rowi. 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, sodp[i][j]is true ifdp[i][j - 1](empty run) ordp[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
Related problems
- Edit Distance · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Delete Operation for Two Strings · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Minimum ASCII Delete Sum for Two Strings · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Distinct Subsequences · same pattern: Dynamic Programming (DP) Patterns
- Burst Balloons · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Path in a Matrix · same pattern: Dynamic Programming (DP) Patterns
- Word Break II · same pattern: Dynamic Programming (DP) Patterns
- Stone Game III · same pattern: Dynamic Programming (DP) Patterns
- Best Time to Buy and Sell Stock III · same pattern: Dynamic Programming (DP) Patterns
- Best Time to Buy and Sell Stock IV · same pattern: Dynamic Programming (DP) Patterns