← Whiteboard questions

Regular Expression Matching

Match a whole string against a small pattern with dot and star

DSA, Hard, 2-D DP

Which structure or algorithm, and what does it cost.

You get a string text and a pattern pattern. The pattern holds letters, . and *. A dot matches any one letter. A star comes right after a letter or a dot and lets it repeat zero or more times in a row. A star never starts the pattern and never follows another star. Return true if the pattern matches the whole of text, and false otherwise.

Examples

Input text = "moon", pattern = "mo*n"
Output true
Why o* repeats the o twice, so the pattern spells m, o, o, n.
Input text = "moon", pattern = "m.*o"
Output false
Why the pattern must end with o, but the text ends with n.
Input text = "", pattern = "a*b*"
Output true
Why both stars repeat zero times, which leaves the empty string.

Constraints

Your answer must contain

Target Aim for O(n * m) time and O(n * m) memory, where n and m are the two lengths.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look only at the front of the pattern. When must its first symbol match the first letter of the text?

Hint 2 the approach

A letter followed by a star gives two choices. Think about what each choice does to the text and to the pattern.

Hint 3 the key step

For a star pair, skip the pair, or use it once on the first text letter and keep it. Fill a text by pattern table, from the ends backwards.

Walkthrough

Full walkthrough brute force to best

Brute force

Recurse on the front of the text and the pattern. At each star, try zero repeats, then one, then two, and so on. The number of calls can grow exponentially, for example for the text of 40 a letters against a pattern of many a-stars followed by b.

Better method

Recursion with memory. Let match(i, j) say whether the text from place i matches the pattern from place j. If pattern[j + 1] is a star, it is match(i, j + 2) (zero repeats) or, when the first letters fit, match(i + 1, j). Otherwise the first letters must fit and match(i + 1, j + 1) must hold. Store each pair. With n * m pairs, the work and the table both stay at O(n * m).

Best method

Fill a table from the ends backwards. ok[i][j] says whether text[i:] matches pattern[j:]. The cell for both ends is true, because an empty text matches an empty pattern. For another cell, first say whether the first letters fit: the text still has a letter, and the pattern symbol is that letter or a dot. If the symbol after pattern[j] is a star, there are two ways to match: skip the pair, which reads ok[i][j + 2], or use it once on this letter and keep the star, which reads ok[i + 1][j] when the first letters fit. If there is no star, the first letters must fit and ok[i + 1][j + 1] must be true. Every cell reads cells with a larger i or j, so going backwards fills them in a safe order. The answer is ok[0][0].

Hand trace

Run on text = "moon", pattern = "mo*n". Row i reads the text from place i, with columns j = 0 to 4 (the pattern from place j), T for true and F for false. Only the last cell of row 4 starts true. i = 4: F F F F T. i = 3: F T F T F. i = 2: F T F F F. i = 1: F T F F F. i = 0: T F F F F. The cell for i = 0, j = 0 is T, so the answer is true.

Code

def pattern_matches(text, pattern):
    n, m = len(text), len(pattern)
    ok = [[False] * (m + 1) for _ in range(n + 1)]   # ok[i][j]: text[i:] matches pattern[j:]
    ok[n][m] = True
    for i in range(n, -1, -1):
        for j in range(m - 1, -1, -1):
            first = i < n and pattern[j] in (text[i], '.')
            if j + 1 < m and pattern[j + 1] == '*':
                ok[i][j] = ok[i][j + 2] or (first and ok[i + 1][j])
            else:
                ok[i][j] = first and ok[i + 1][j + 1]
    return ok[0][0]

Time and memory

O(n * m) time, one step per cell. O(n * m) memory for the table, where n and m are the lengths of the text and the pattern.

Common mistakes

  • Treating a star as a wildcard for any letters. Here a star repeats the symbol before it, so m.*o is how you write anything between m and o.
  • Reading the symbol after pattern[j] without checking that it exists. At the last place of the pattern there is no next symbol.
  • Returning true as soon as the pattern ends. The text must be used up too, so the cell for both ends is the only start.

Related problems

More 2-D DP problems
Regular Expression Matching: walkthrough and Python solution