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?
  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

'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

Exams that ask this topic