SDE & MLE Prep

44. Wildcard Matching

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]