Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match.

Problem: Wildcard matching where '?' matches one character and '*' matches any sequence (including empty); the whole string must match.
def match(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):
        dp[0][j] = dp[0][j-1] and p[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][j-1] or dp[i-1][j]
            else: dp[i][j] = dp[i-1][j-1] and p[j-1] in (s[i-1], '?')
    return dp[-1][-1]
print(match("xaylmz", "x?y*z"), match("aaab", "a*?b*b"), match("", "***"))
What is printed?
  1. A. True False True
  2. B. True True True
  3. C. False False True
  4. D. True False False

Correct answer: A. True False True

'x?y*z': x, a, y, then * absorbs 'lm', then z — match. 'a*?b*b' needs two b's after the first a (one for 'b', one for the final 'b'), but 'aaab' has only one b, so False. '***' matches the empty string.

More Coding Interview Problems questions

Exams that ask this topic