Start learning free

LESSON 536 OF 673 · DYNAMIC PROGRAMMING

Regular Expression Matching in Python: O(m·n) Dynamic Programming

Practice O(m · n) Read the full explanation

You get a pattern p and a string s.

Return True if the pattern matches all of s. Otherwise, return False.

The pattern holds lowercase letters, dots and stars:

  • A letter matches that same letter.
  • A dot (.) matches any one letter.
  • A star (*) always comes right after a letter or a dot. It repeats that letter or dot zero or more times.

So b* matches "", "b", "bb" and so on. And .* matches any string, even an empty one.

The pattern must match the whole of s. Matching only a part of it is not enough.

 

Example 1:

Input: s = "moon", p = "mo*n"
Output: True
Explanation: m matches the m.
o* matches the two o's.
n matches the n.

Example 2:

Input: s = "seat", p = "s.a"
Output: False
Explanation: s matches the s, the dot matches the e, and a matches the a.
The t is left over, so the whole string doesn't match.

Example 3:

Input: s = "abc", p = "x*a.*"
Output: True
Explanation: x* matches zero x's, before the a.
a matches the a.
.* matches the rest, "bc".

 

Constraints:

  • s has 0 to 1,000 letters.
  • p has 0 to 1,000 characters.
  • s holds lowercase English letters only.
  • p holds lowercase English letters, dots and stars.
  • Every star comes right after a letter or a dot.

Note:

Your solution should run in O(m · n) time. Here m and n are the lengths of s and p.



Trying each way a star could match, one after another, can take exponential time. Think of "a*a*a*a*b" against many a's: every way to share the a's among the stars gets tried.
The same question comes back again and again: does s from index i match p from index j? Store each answer in a table dp[i][j], so it is worked out only once.

Fill the table from the end. dp[m][n] is true: an empty rest matches an empty rest.
For each cell, first check if p[j] matches s[i]: the same letter, or a dot. Then look at the next character of the pattern.
  • When p[j + 1] is a star, the pair can match nothing: dp[i][j + 2]. Or it can match s[i] and stay for more: dp[i + 1][j], when the first letter matches.
  • Otherwise, p[j] must match s[i], and the rest must match too: dp[i + 1][j + 1].
The answer is dp[0][0].

The table has (m + 1) × (n + 1) cells. Each one takes a constant amount of work. That is O(m · n) time and O(m · n) space.
STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Regular Expression Matching in Python, explained

    Problem overview

    The method isMatch receives a string s and a pattern p. It returns True if the pattern matches all of s, and False otherwise. The pattern holds lowercase letters, dots and stars:

    • A letter matches that same letter.
    • A dot (.) matches any one letter.
    • A star (*) always comes right after a letter or a dot and repeats it zero or more times. So b* matches "", "b", "bb" and so on, and .* matches any string, even an empty one.

    The pattern must match the whole of s: matching only a part is not enough. Both strings can be empty, and each has at most 1,000 characters.

    For s = "moon" and p = "mo*n" the result is True: m matches m, o* matches both os, and n matches n. For "seat" and "s.a" the result is False: the dot matches the e and a matches a, but the t is left over. For "abc" and "x*a.*" the result is True: x* matches zero xs, a matches a, and .* matches "bc".

    The statement asks for O(m · n) time, where m and n are the lengths of s and p.

    Approach: does s from index i match p from index j?

    The obvious recursive search tries every way a star could match: zero letters, one letter, two letters, and so on. The same question comes back again and again, because different choices for earlier stars can leave you at the same place in both strings. With p = "a*a*a*a*b" and a string of as, the work grows quickly with the length, and every extra star in the pattern multiplies it.

    The fix is to name the repeated question: does s from index i match p from index j? Store each answer in a table, dp[i][j], so it is worked out once. There are (m + 1) × (n + 1) such questions, and each one is answered from a few other cells in constant time.

    The base case is dp[m][n]: an empty rest of s matches an empty rest of p. For any other cell, first ask whether p[j] matches s[i]: it does if i is inside s and p[j] is the same letter or a dot. Then look at the next pattern character:

    • It is a star. The pair p[j] p[j + 1] can match nothing, which leaves dp[i][j + 2]. Or, if the first letter matches, it can match s[i] and stay available for more letters, which leaves dp[i + 1][j]. Either one is enough.
    • It is not a star. p[j] must match s[i], and the rest must match too: dp[i + 1][j + 1].

    Every cell reads cells below it or to its right, so the table is filled from the end. The answer is dp[0][0].

    Step by step

    1. Store the lengths in m = len(s) and n = len(p).
    2. Create the table. dp has m + 1 rows of n + 1 values, all False. The extra row and column stand for an empty rest. A list comprehension makes a separate row for each i.
    3. Set dp[m][n] = True. The rest of column n stays False, because an empty pattern can't match letters.
    4. Loop over i from m down to 0 with range(m, -1, -1). Row m must be filled too, because a pattern like a* can match an empty rest.
    5. Loop over j from n - 1 down to 0. Column n is already set.
    6. Compute firstMatch: i < m and (p[j] == s[i] or p[j] == '.'). The test i < m comes first so that s[i] is never read when s is used up.
    7. Handle a star. Check j + 1 < n before reading p[j + 1]. If it is a star, dp[i][j] is dp[i][j + 2] or (firstMatch and dp[i + 1][j]).
    8. Handle a plain character. Otherwise, dp[i][j] is firstMatch and dp[i + 1][j + 1].
    9. Return dp[0][0], the answer for all of s and all of p.

    The solution in Python

    class Solution:
        def isMatch(self, s: str, p: str) -> bool:
            m = len(s)
            n = len(p)
            dp = [[False] * (n + 1) for _ in range(m + 1)]
            dp[m][n] = True
            for i in range(m, -1, -1):
                for j in range(n - 1, -1, -1):
                    firstMatch = i < m and (p[j] == s[i] or p[j] == '.')
                    if j + 1 < n and p[j + 1] == '*':
                        dp[i][j] = dp[i][j + 2] or (firstMatch and dp[i + 1][j])
                    else:
                        dp[i][j] = firstMatch and dp[i + 1][j + 1]
            return dp[0][0]
    

    Python details worth noting:

    • A list comprehension for the rows. [[False] * (n + 1) for _ in range(m + 1)] builds a new inner list for every row. Writing [[False] * (n + 1)] * (m + 1) would repeat one inner list m + 1 times, and setting one cell would change the same column in every row.
    • and and or short-circuit. In i < m and (...), the right side is skipped when i < m is false, so s[i] is never read out of range. Reading "a"[1] raises IndexError: string index out of range. The same goes for j + 1 < n and p[j + 1] == '*'.
    • firstMatch is a real boolean. i < m and the comparisons are booleans, so and and or give True or False here, and every cell of the table holds one of the two.
    • range(m, -1, -1) counts down from m to 0. The end value -1 is excluded.
    • Single quotes around '.' and '*' are the same as double quotes. Python has no separate character type: these are one-letter strings.

    The table for "moon" and "mo*n"

    Here is the table after the loops finish, with T for True and a dot for False. Rows are positions in s and columns are positions in p; end is the empty rest in each:

          m    o    *    n    end
    m     T    .    .    .    .
    o     .    T    .    .    .
    o     .    T    .    .    .
    n     .    T    .    T    .
    end   .    .    .    .    T
    

    The cell in the top left, dp[0][0], is True, which is the answer. Reading the column of o* (the second column), rows 1, 2 and 3 are True: "oon", "on" and "n" all match o*n, where the star takes two, one and zero letters.

    Why the table beats plain recursion

    Counting calls of a plain recursive version of the same rules, for the pattern "a*a*a*a*b" against a string of as that never matches, gives 2,365 calls for 10 letters, 23,275 for 20 and 98,735 for 30. The table for the 30-letter string has 31 × 11 = 341 cells, and each is computed once.

    Results

    isMatch("moon", "mo*n") = True
    isMatch("seat", "s.a") = False
    isMatch("abc", "x*a.*") = True
    isMatch("", "a*") = True
    isMatch("", "") = True
    isMatch("a", "") = False
    isMatch("", ".") = False
    isMatch("aa", "a") = False
    isMatch("aa", "a*") = True
    isMatch("ab", ".*") = True
    isMatch("aab", "c*a*b") = True
    isMatch("mississippi", "mis*is*p*.") = False
    

    Complexity

    Time: O(m · n). The table has (m + 1) × (n + 1) cells, and each cell is computed once from at most two other cells.

    Space: O(m · n). The table is the extra memory. For two strings of 1,000 characters that is about a million entries.

    Edge cases and common mistakes

    • An empty string against a starred pattern. isMatch("", "a*") is True, because the star matches zero letters. This is why row m of the table is filled too.
    • An empty pattern. isMatch("a", "") is False, and isMatch("", "") is True.
    • A dot needs a letter. isMatch("", ".") is False: a dot matches exactly one letter, never nothing. firstMatch is False when i == m.
    • Leftover letters. The pattern must cover all of s. In the second example, matching s.a against the start of "seat" is not enough.
    • Treating the star as its own character. A star belongs to the character before it, and the pair is handled together. That is why the star branch looks at j + 2 and why the loop never has to handle a star on its own.
    • Forgetting the zero case. Without dp[i][j + 2], patterns like x*a.* fail, because x* must be allowed to match nothing.
    • Reading p[j + 1] without checking j + 1 < n. At the last pattern character there is no next character, and the index would be out of range.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free