Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty).

Problem: Wildcard matching over the whole string: '?' matches any one character, '*' matches any sequence (including empty).
def wild(s, p):
    dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
    dp[0][0] = True
    for j in range(1, len(p) + 1):
        if p[j - 1] == "*": dp[0][j] = dp[0][j - 1]
    for i in range(1, len(s) + 1):
        for j in range(1, len(p) + 1):
            if p[j - 1] == "*": dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
            elif p[j - 1] in ("?", s[i - 1]): dp[i][j] = dp[i - 1][j - 1]
    return dp[-1][-1]
print(wild("report.pdf", "*.p?f"), wild("data", "d*t*a*"), wild("abc", "a?"), wild("", "**"))
What is printed?
  1. A. True True True True
  2. B. True True False True
  3. C. True True False False
  4. D. True False False True

Correct answer: B. True True False True

For '*', dp[i−1][j] lets it absorb one more character and dp[i][j−1] lets it match nothing. "report.pdf" = "report" + ".p" + 'd' + 'f'. "d*t*a*": the trailing '*' matches the empty string. "a?" covers only two characters, so "abc" fails (no implicit '*' at the end). An empty string matches "**" thanks to the first-row initialisation. O(|s|·|p|).

More Coding Interview Problems questions

Exams that ask this topic