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?- A. True False True
- B. True True True
- C. False False True
- 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
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…
- A suffix array of a string of length n is built by putting all suffixes in a list and sorting them with a comparison sort, where each…