Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match).
Problem: Regular-expression matching where '.' matches any one character and 'x*' matches zero or more x (the whole string must match).
from functools import lru_cache
def match(s, p):
@lru_cache(None)
def f(i, j):
if j == len(p): return i == len(s)
first = i < len(s) and p[j] in (s[i], '.')
if j + 1 < len(p) and p[j+1] == '*':
return f(i, j + 2) or (first and f(i + 1, j))
return first and f(i + 1, j + 1)
return f(0, 0)
print(match("aaa", "ab*a*c*a"), match("abcd", "d*"), match("", "a*b*"))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
'ab*a*c*a': a, then b* empty, a* takes one a, c* empty, final a: matches 'aaa'. 'd*' can only produce d's, so 'abcd' fails. 'a*b*' can match the empty string by taking zero of each.
More Coding Interview Problems questions
- Problem: Count how many distinct index sequences of s spell t as a subsequence. python def distinct(s, t): dp = [1] + [0] len(t) for c in…
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…
- Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp). python INF…
- Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set. python def…
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…
- Problem: Extended Euclid returns g = gcd(a, b) and integers x, y with a·x + b·y = g. python def eg(a, b): if b == 0: return a, 1, 0 g, x…