10. Regular Expression Matching
Asked at 24Amazon55Bloomberg54Google51Meta48Apple46Microsoft45Netskope100X94Rokt81Zoho81Waymo67Airbnb66ByteDance59Coupang58Two Sigma58Sprinklr54TikTok53PhonePe53Uber52Snowflake48Infosys45Accenture44tcs36Oracle27
Problem
Implement regular expression matching where . matches any single character and * matches zero or more of the element before it. The pattern must match the entire string s.
Example: s = "aa", p = "a" → false; p = "a*" → true; s = "ab", p = ".*" → true
Constraints: lengths ≤ 20; every * follows a valid character.
dp[i][j] = s[i:] matches p[j:] (suffix form reads naturally). first = i < len(s) and p[j] in {s[i], '.'}. If p[j+1] == '*': skip x* (dp[i][j+2]) or consume one char (first and dp[i+1][j]); else first and dp[i+1][j+1].
Complexity: O(m·n).
class Solution:
def isMatch(self, s: str, p: str) -> bool:
@cache
def dp(i, j):
if j == len(p):
return i == len(s)
first = i < len(s) and p[j] in (s[i], ".")
if j + 1 < len(p) and p[j + 1] == "*":
return dp(i, j + 2) or (first and dp(i + 1, j))
return first and dp(i + 1, j + 1)
return dp(0, 0)
assert Solution().isMatch("aa", "a") is False
assert Solution().isMatch("aa", "a*") is True
assert Solution().isMatch("ab", ".*") is True
assert Solution().isMatch("aab", "c*a*b") is True
assert Solution().isMatch("mississippi", "mis*is*p*.") is False
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[m][n] = true;
for (int i = m; i >= 0; i--)
for (int j = n - 1; j >= 0; j--) {
boolean first = i < m && (p.charAt(j) == s.charAt(i) || p.charAt(j) == '.');
if (j + 1 < n && p.charAt(j + 1) == '*') dp[i][j] = dp[i][j + 2] || (first && dp[i + 1][j]);
else dp[i][j] = first && dp[i + 1][j + 1];
}
return dp[0][0];
}
}
func isMatch(s string, p string) bool {
memo := map[[2]int]bool{}
var dp func(i, j int) bool // does s[i:] match p[j:]?
dp = func(i, j int) bool {
if j == len(p) {
return i == len(s)
}
key := [2]int{i, j}
if v, ok := memo[key]; ok {
return v
}
first := i < len(s) && (p[j] == s[i] || p[j] == '.')
var res bool
if j+1 < len(p) && p[j+1] == '*' {
res = dp(i, j+2) || (first && dp(i+1, j)) // skip "x*", or use it once more
} else {
res = first && dp(i+1, j+1)
}
memo[key] = res
return res
}
return dp(0, 0)
}