LeetCode #44 Hard

Wildcard Matching

Wildcard Matching is LeetCode 44 (Hard). Given a string s and a pattern p, return true if the pattern matches the whole string, not just part of it. In the pattern:

  • ? matches exactly one character,
  • * matches any run of characters, including none,
  • every other letter matches only itself.

Both strings can be empty and up to 2,000 characters long, so trying every way to split the string among the stars is far too slow.

Constraints
  • 0 <= s.length, p.length <= 2000
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '?' or '*'.
stringdynamic-programminggreedy
Open on LeetCode ↗
02

Intuition

Letters and ? leave no choice: each one must match the next character of s. Only a star has a choice, namely how many characters it swallows. So try the cheapest option first, zero characters, and remember where that star was.

If a later character fails to match, go back to the most recent star only and let it swallow one more character. Earlier stars never need a second look: any extra text they could have taken, the last star can take instead, because a star matches anything.

How to spot this pattern

Matching a pattern with wildcards against a whole string is a two-string matching problem, normally solved with a table over prefixes. Regular Expression Matching looks similar, but there * repeats the character before it, so the last-star shortcut does not apply and the table is required.

03

Approach

Try it first

Before reading on, match adceb against *a*b by hand. Which star should give back or take characters when you reach the final b? Aim for O(1) extra space.

1

Walk both strings with two pointers

Keep i in s and j in p. If p[j] is ? or the same letter as s[i], move both forward. That match is forced, so there is nothing to remember.

2

On a star, save it and take zero characters

Record star = j and mark = i, then move only j. Matching zero characters first is the cheapest guess, and the saved pair is the place to come back to if the guess turns out short.

3

On a mismatch, give the last star one more character

If a star was saved, set mark += 1, i = mark and j = star + 1. The star now covers one more character of s and the pattern after it starts again from the next one. With no star saved, the mismatch is final, so return false.

4

Let leftover stars match nothing

When s runs out, skip any stars left in p, since each can match zero characters. The answer is true only if that reaches the end of the pattern; a leftover letter or ? needs a character that is not there.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isMatch(self, s: str, p: str) -> bool:
▶3 i = j = 0
▶4 star, mark = -1, 0
▶5 while i < len(s):
▶6 if j < len(p) and (p[j] == "?" or p[j] == s[i]):
▶7 i += 1
▶8 j += 1
▶9 elif j < len(p) and p[j] == "*":
▶10 star, mark = j, i
▶11 j += 1
▶12 elif star != -1:
▶13 mark += 1
▶14 i, j = mark, star + 1
▶15 else:
▶16 return False
▶17 while j < len(p) and p[j] == "*":
▶18 j += 1
▶19 return j == len(p)
spadceb*a*bijstar takes nothing yetstar at 0 → save it, let it take nothing
i0
j0
starat 0takes 0
A star may take any number of characters. Try the cheapest choice, none, and save where the star is and where s stood, so a later mismatch can come back and give it more.
spadceb*a*bijsavedstar takes nothing yet'a' matches 'a' → move both pointers
i0
j1
starat 0takes 0
The letters are equal, and there is no other way to use this pattern character, so both pointers move on without remembering anything.
spadceb*a*bijstar takes nothing yetstar at 2 → save it, let it take nothing
i1
j2
starat 2takes 0
A star may take any number of characters. Try the cheapest choice, none, and save where the star is and where s stood, so a later mismatch can come back and give it more.
spadceb*a*bijsavedstar takes nothing yet'd' does not match 'b' → star takes one more
i1
j3
starat 2takes 0
'd' cannot match 'b'. The guess for the saved star was too short, so it swallows one more character and the pattern after it starts again.
spadceb*a*bijsavedtaken by the starstar now takes 1 → restart after it
i2
j3
starat 2takes 1
The star covers 1 character now. Only this latest star is ever widened: any text an earlier star could have taken, this one can take instead.
spadceb*a*bijsavedtaken by the star'c' does not match 'b' → star takes one more
i2
j3
starat 2takes 1
'c' cannot match 'b'. The guess for the saved star was too short, so it swallows one more character and the pattern after it starts again.
spadceb*a*bijsavedtaken by the starstar now takes 2 → restart after it
i3
j3
starat 2takes 2
The star covers 2 characters now. Only this latest star is ever widened: any text an earlier star could have taken, this one can take instead.
spadceb*a*bijsavedtaken by the star'e' does not match 'b' → star takes one more
i3
j3
starat 2takes 2
'e' cannot match 'b'. The guess for the saved star was too short, so it swallows one more character and the pattern after it starts again.
spadceb*a*bijsavedtaken by the starstar now takes 3 → restart after it
i4
j3
starat 2takes 3
The star covers 3 characters now. Only this latest star is ever widened: any text an earlier star could have taken, this one can take instead.
spadceb*a*bijsavedtaken by the star'b' matches 'b' → move both pointers
i4
j3
starat 2takes 3
The letters are equal, and there is no other way to use this pattern character, so both pointers move on without remembering anything.
spadceb*a*biendjendsavedtaken by the starboth used up → the pattern matches, true
j4
len(p)4
resulttrue
Every character of s is accounted for and the pattern is finished, so the whole string matches.
05

DP table over prefixes

Let dp[i][j] say whether the first i characters of s match the first j characters of p. The empty string matches the empty pattern, and it matches a pattern prefix only while that prefix is all stars. For a letter or ?, copy the answer for both prefixes one shorter. For a star, it either matches nothing (dp[i][j - 1]) or swallows s[i - 1] and stays available (dp[i - 1][j]). The answer is dp[m][n].

▶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 j in range(1, n + 1):
▶7 dp[0][j] = dp[0][j - 1] and p[j - 1] == "*"
▶8 for i in range(1, m + 1):
▶9 for j in range(1, n + 1):
▶10 if p[j - 1] == "*":
▶11 dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
▶12 elif p[j - 1] == "?" or p[j - 1] == s[i - 1]:
▶13 dp[i][j] = dp[i - 1][j - 1]
▶14 return dp[m][n]
06

Common pitfalls

Reading p[j] after the pattern has run out

✗ Wrong
if p[j] == "?" or p[j] == s[i]:
✓ Right
if j < len(p) and (p[j] == "?" or p[j] == s[i]):

For s = "aa", p = "a", the second a of s is compared when j is already 1, past the end of the pattern. Python raises IndexError and C++ reads past the string.

Returning as soon as s is used up

✗ Wrong
return j == len(p)
✓ Right
skip the remaining '*' first, then return j == len(p)

For s = "ab", p = "ab*", the string ends with j on the star, so the check says false. The trailing star can match nothing, so the answer is true.

07

Edge cases

Empty string, pattern of stars only, like "" and "**"

The main loop never runs, the tail loop skips both stars, and the answer is true.

Non-empty string, empty pattern

The first character has nothing to match and no star was saved, so the answer is false at once.

08

Complexity

Time
O(m · n) worst case
Space
O(1)
Each retry moves mark one place to the right, so there are at most m retries, and after each one the pattern part after the star can be re-read in full. A long run of a in s against * followed by many a and a final b reaches that bound; typical inputs run close to O(m + n). The DP table version is O(m · n) time on every input and O(m · n) space.
09

Wildcard Matching FAQ

Why can the last star be trusted to fix every earlier mistake?

The pattern before the last star was matched with as few characters as possible, so the text after the last star could start at the earliest place it is allowed. Any other choice only pushes that start to the right, and the last star can stretch to reach any later start. Starting from the earliest place therefore loses nothing.

Is the greedy version fine in an interview, or do they expect the DP?

Many interviewers expect the DP table because it is easy to argue correct. The greedy is a strong follow-up when they ask to cut the space, as long as you can explain why only the last star matters.