LeetCode #10 Hard

Regular Expression Matching

Regular Expression Matching is LeetCode 10 (Hard). Given a string s and a pattern p, return whether the pattern matches all of s, not just part of it. The pattern has two special characters:

  • . matches any one character.
  • * means zero or more copies of the character just before it. So a* is one unit that matches "", "a", "aa", and so on, and .* matches any run of characters.

Both strings are at most 20 characters long.

Constraints
  • 1 <= s.length <= 20
  • 1 <= p.length <= 20
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '.', and '*'.
  • Every '*' has a valid character before it.
stringdynamic-programmingrecursion
Open on LeetCode ↗
02

Intuition

The only hard part is a starred unit like a*: it does not say how many characters to eat. Trying one guess fails, because eating too many can starve the rest of the pattern.

So let a table decide. dp[i][j] answers does the first i characters of s match the first j characters of p? A plain character or . must match the last character of s and leave the rest to dp[i-1][j-1]. A starred unit has two choices, and the cell is true if either works:

  • Use it zero times: drop the two pattern characters, dp[i][j-2].
  • Use it once more: if it matches s[i-1], drop that character but keep the unit, dp[i-1][j].
How to spot this pattern

Two strings are matched left to right, and one token can consume a variable amount of the other. Whenever a choice now affects what is left later, and the same "prefix of one, prefix of the other" situation is reached by many choice paths, a 2D table over the two prefix lengths removes the repeated work.

03

Approach

Try it first

Before reading on: why does "aab" match "c*a*b"? Which unit is used zero times, and how many characters does a* take? Then write dp[i][j] for a starred p[j-1] in terms of smaller cells. Aim for O(m · n) time.

1

Start from the empty match

dp[0][0] is true: an empty pattern matches an empty string. Every other cell starts false and is filled from cells above and to the left, so filling rows top to bottom and columns left to right always reads finished cells.

2

Row 0 still matters

Row i = 0 asks whether a pattern prefix matches the empty string. Only starred units used zero times can do that, so a*b* gives true at columns 2 and 4. The same zero-copies rule fills this row; no special loop is needed.

3

A letter or a dot

If p[j-1] is not *, the cell is true only when i > 0, p[j-1] equals s[i-1] or is ., and dp[i-1][j-1] is true. Both strings lose their last character and the shorter question is already answered.

4

A star: zero copies or one more

If p[j-1] is *, its unit is p[j-2]. Zero copies reads dp[i][j-2]. One more copy needs p[j-2] to match s[i-1], then reads dp[i-1][j]: the same column, because the unit may keep eating. Those two cells together cover every count of copies.

5

Read the corner

dp[m][n] compares the whole string with the whole pattern, which is the answer. A partial match never counts, because only this cell is returned.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isMatch(self, s: str, p: str) -> bool:
▶3 m, n = len(s), len(p)
▶4 dp = [[False] * (n + 1) for _ in range(m + 1)]
▶5 dp[0][0] = True
▶6 for i in range(m + 1):
▶7 for j in range(1, n + 1):
▶8 if p[j - 1] == "*":
▶9 zero = dp[i][j - 2]
▶10 more = i > 0 and p[j - 2] in (s[i - 1], ".") and dp[i - 1][j]
▶11 dp[i][j] = zero or more
▶12 else:
▶13 dp[i][j] = i > 0 and p[j - 1] in (s[i - 1], ".") and dp[i - 1][j - 1]
▶14 return dp[m][n]
patternemptyc*a*bemptyTaFaFbFempty vs emptynothing to matchempty matches empty: true
s"aab"
p"c*a*b"
The table. Row i is the first i letters of the string, column j the first j characters of the pattern, and each cell says whether they match. The top-left cell compares nothing with nothing, so it is true. The rest of the left column is false, since a non-empty string never matches an empty pattern. Every other cell is filled from cells above and to the left of it.
patternemptyc*a*bemptyTFaFaFbFc needs a letterstring is empty=Fthis cellc cannot match an empty string
string partempty
pattern part'c'
empty against 'c'. The pattern ends in c, which must eat exactly one letter, and the string part is empty.
patternemptyc*a*bemptyTFTaFaFbFzero c: T2 columns leftorone more: no letternothing to eat=Tthis cellc* used zero times: true
string partempty
pattern part'c*'
empty against 'c*'. The pattern ends in the unit c*. Using it zero times means empty must match empty: true. There is no letter for it to eat. The cell is true.
patternemptyc*a*bemptyTFTFaFaFbFa needs a letterstring is empty=Fthis cella cannot match an empty string
string partempty
pattern part'c*a'
empty against 'c*a'. The pattern ends in a, which must eat exactly one letter, and the string part is empty.
patternemptyc*a*bemptyTFTFTaFaFbFzero a: T2 columns leftorone more: no letternothing to eat=Tthis cella* used zero times: true
string partempty
pattern part'c*a*'
empty against 'c*a*'. The pattern ends in the unit a*. Using it zero times means empty must match 'c*': true. There is no letter for it to eat. The cell is true.
patternemptyc*a*bemptyTFTFTFaFaFbFb needs a letterstring is empty=Fthis cellb cannot match an empty string
string partempty
pattern part'c*a*b'
empty against 'c*a*b'. The pattern ends in b, which must eat exactly one letter, and the string part is empty.
patternemptyc*a*bemptyTFTFTFaFFaFbFc is not alast charactersandbefore: Tup and left=Fthis cellc does not fit a: false
string part'a'
pattern part'c'
'a' against 'c'. c is not the last letter a, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFaFbFzero c: F2 columns leftorc can't be acell above=Fthis cellc* can't help: false
string part'a'
pattern part'c*'
'a' against 'c*'. The pattern ends in the unit c*. Using it zero times means 'a' must match empty: false. c does not match the last letter a, so eating is not an option. The cell is false.
patternemptyc*a*bemptyTFTFTFaFFFTaFbFa fits alast charactersandbefore: Tup and left=Tthis cella fits a and the rest matched: true
string part'a'
pattern part'c*a'
'a' against 'c*a'. a equals the last letter. Both lose their last character, and the cell up and to the left says whether empty matches 'c*': true.
patternemptyc*a*bemptyTFTFTFaFFFTTaFbFzero a: F2 columns leftorone more a: Tcell above=Tthis cella* eats one more a: true
string part'a'
pattern part'c*a*'
'a' against 'c*a*'. The pattern ends in the unit a*. Using it zero times means 'a' must match 'c*': false. It can eat the last letter a, and then empty must match 'c*a*', with the unit still available: true. The cell is true.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFbFb is not alast charactersandbefore: Tup and left=Fthis cellb does not fit a: false
string part'a'
pattern part'c*a*b'
'a' against 'c*a*b'. b is not the last letter a, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFbFc is not alast charactersandbefore: Fup and left=Fthis cellc does not fit a: false
string part'aa'
pattern part'c'
'aa' against 'c'. c is not the last letter a, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFbFzero c: F2 columns leftorc can't be acell above=Fthis cellc* can't help: false
string part'aa'
pattern part'c*'
'aa' against 'c*'. The pattern ends in the unit c*. Using it zero times means 'aa' must match empty: false. c does not match the last letter a, so eating is not an option. The cell is false.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFbFa fits alast charactersandbefore: Fup and left=Fthis cella fits, but the rest failed: false
string part'aa'
pattern part'c*a'
'aa' against 'c*a'. a equals the last letter. Both lose their last character, and the cell up and to the left says whether 'a' matches 'c*': false.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTbFzero a: F2 columns leftorone more a: Tcell above=Tthis cella* eats one more a: true
string part'aa'
pattern part'c*a*'
'aa' against 'c*a*'. The pattern ends in the unit a*. Using it zero times means 'aa' must match 'c*': false. It can eat the last letter a, and then 'a' must match 'c*a*', with the unit still available: true. The cell is true.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFb is not alast charactersandbefore: Tup and left=Fthis cellb does not fit a: false
string part'aa'
pattern part'c*a*b'
'aa' against 'c*a*b'. b is not the last letter a, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFc is not blast charactersandbefore: Fup and left=Fthis cellc does not fit b: false
string part'aab'
pattern part'c'
'aab' against 'c'. c is not the last letter b, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFFzero c: F2 columns leftorc can't be bcell above=Fthis cellc* can't help: false
string part'aab'
pattern part'c*'
'aab' against 'c*'. The pattern ends in the unit c*. Using it zero times means 'aab' must match empty: false. c does not match the last letter b, so eating is not an option. The cell is false.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFFFa is not blast charactersandbefore: Fup and left=Fthis cella does not fit b: false
string part'aab'
pattern part'c*a'
'aab' against 'c*a'. a is not the last letter b, so this cell is false whatever came before.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFFFFzero a: F2 columns leftora can't be bcell above=Fthis cella* can't help: false
string part'aab'
pattern part'c*a*'
'aab' against 'c*a*'. The pattern ends in the unit a*. Using it zero times means 'aab' must match 'c*': false. a does not match the last letter b, so eating is not an option. The cell is false.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFFFFTb fits blast charactersandbefore: Tup and left=Tthis cellb fits b and the rest matched: true
string part'aab'
pattern part'c*a*b'
'aab' against 'c*a*b'. b equals the last letter. Both lose their last character, and the cell up and to the left says whether 'aa' matches 'c*a*': true.
patternemptyc*a*bemptyTFTFTFaFFFTTFaFFFFTFbFFFFFTall of "aab" vs all of "c*a*b"bottom-right cellanswer: true, the whole string matches
returntrue
Read the bottom-right cell. It compares the whole string with the whole pattern, which is the question asked. It is true.
05

Recursion with a cache

match(i, j) looks at what comes next in the pattern. If the next unit is starred, it either skips the unit (j + 2) or, when the first character matches, eats one character and keeps the unit (i + 1). Without the cache the same (i, j) is solved again on every path that reaches it, which is exponential.

▶1class Solution:
▶2 def isMatch(self, s: str, p: str) -> bool:
▶3 @cache
▶4 def match(i, j):
▶5 if j == len(p):
▶6 return i == len(s)
▶7 first = i < len(s) and p[j] in (s[i], ".")
▶8 if j + 1 < len(p) and p[j + 1] == "*":
▶9 return match(i, j + 2) or (first and match(i + 1, j))
▶10 return first and match(i + 1, j + 1)
▶11 
▶12 return match(0, 0)
06

Common pitfalls

Letting a star eat as much as it can

✗ Wrong
# a* takes every 'a' it sees, then move on
while i < m and p[j] in (s[i], '.'):
    i += 1
j += 2
✓ Right
dp[i][j] = dp[i][j - 2] or (matches and dp[i - 1][j])

s = "aaa", p = "a*a" should be true, with a* taking two letters and the last a taking one. Greedy a* eats all three, the final a finds nothing, and the answer comes out false. Every count of copies has to stay possible.

Reading the star's unit from the wrong place

✗ Wrong
more = p[j - 1] in (s[i - 1], '.') and dp[i - 1][j]
✓ Right
more = p[j - 2] in (s[i - 1], '.') and dp[i - 1][j]

p[j - 1] is the * itself, which never equals a letter, so the one-more branch never fires and "aa" against "a*" returns false. The repeated character is the one before the star.

Stopping when the string runs out

✗ Wrong
if i == len(s):
    return j == len(p)
✓ Right
if j == len(p):
    return i == len(s)

An empty rest of s can still match a pattern rest like b*c*, by using each unit zero times. For s = "a", p = "ab*" the wrong base returns false once a is matched, though the answer is true.

07

Edge cases

Pattern made only of starred units, such as a*b*

Row 0 of the table carries true across columns 2 and 4, so it matches the empty prefix and any run of a's followed by b's.

.* in the middle, such as a.*b

The unit matches any run of characters, including none, so the table checks every split point between the leading a and the final b.

08

Complexity

Time
O(m · n)
Space
O(m · n)
There are (m + 1) · (n + 1) cells, and each reads at most two others. Each row only reads itself and the row above, so two rows of length n + 1 are enough if memory matters.
09

Regular Expression Matching FAQ

How is this different from wildcard matching?

In Wildcard Matching * stands alone and matches any run of characters, while ? matches one. Here * is attached to the character before it and only repeats that character, so a* cannot match b. That is why this table reads p[j-2] and jumps back two columns, while the wildcard table only looks one column back.

Can Python's re module solve it?

re.fullmatch(p, s) is not None gives the same answer, because . and * mean the same thing there and fullmatch requires the whole string. Interviews expect the table, and the library uses a backtracking engine that can be slow on some patterns.

Why does the one-more choice stay in column j?

After eating one character, the starred unit is still available for the next character, so the pattern position does not move. Staying in the same column is how one cell covers one, two, three or more copies: each step up the column eats one more.