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?- A. True True True True
- B. True True False True
- C. True True False False
- 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
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second…
- Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track…
- Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with…
- Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted. python def roman(s): v = {"I": 1, "V"…