44. Wildcard Matching
Asked at 17Bloomberg47Microsoft45Google42Amazon39Meta36X94Two Sigma90DP world88Zoho83Snap80Coupang76Instacart69Walmart Labs53Infosys45DE Shaw38Atlassian34Oracle27
Problem
Implement wildcard matching where ? matches any single character and * matches any sequence of characters (including the empty one). The pattern must match the entire string s.
Example: s = "aa", p = "a" → false; p = "*" → true; s = "cb", p = "?a" → false
Constraints: lengths ≤ 2000.
dp[i][j] = s[:i] matches p[:j]. ? or equal char → dp[i−1][j−1]; * → dp[i][j−1] (matches empty) or dp[i−1][j] (absorbs one more char). Base: leading *s match the empty string.
Complexity: O(m·n) time, O(n) space.
class Solution:
def isMatch(self, s: str, p: str) -> bool:
n = len(p)
dp = [True] + [False] * n
for j in range(1, n + 1):
dp[j] = dp[j - 1] and p[j - 1] == "*"
for ch in s:
diag, dp[0] = dp[0], False
for j in range(1, n + 1):
up = dp[j]
if p[j - 1] == "*":
dp[j] = dp[j - 1] or up
else:
dp[j] = diag and p[j - 1] in (ch, "?")
diag = up
return dp[n]
assert Solution().isMatch("aa", "a") is False
assert Solution().isMatch("aa", "*") is True
assert Solution().isMatch("cb", "?a") is False
assert Solution().isMatch("adceb", "*a*b") is True
assert Solution().isMatch("acdcb", "a*c?b") 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[0][0] = true;
for (int j = 1; j <= n; j++) dp[0][j] = dp[0][j - 1] && p.charAt(j - 1) == '*';
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
else dp[i][j] = dp[i - 1][j - 1] && (pc == '?' || pc == s.charAt(i - 1));
}
return dp[m][n];
}
}
func isMatch(s string, p string) bool {
n := len(p)
dp := make([]bool, n+1) // dp[j]: the current prefix of s matches p[:j]
dp[0] = true
for j := 1; j <= n; j++ {
dp[j] = dp[j-1] && p[j-1] == '*'
}
for i := 0; i < len(s); i++ {
diag := dp[0]
dp[0] = false
for j := 1; j <= n; j++ {
up := dp[j]
if p[j-1] == '*' {
dp[j] = dp[j-1] || up // '*' matches nothing, or one more character
} else {
dp[j] = diag && (p[j-1] == s[i] || p[j-1] == '?')
}
diag = up
}
}
return dp[n]
}