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.
- 0 <= s.length, p.length <= 2000
- s contains only lowercase English letters.
- p contains only lowercase English letters, '?' or '*'.
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.
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.
Approach
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.
Two ways to solve it
Match forced characters, save the latest star, and on a mismatch let that star take one more character.
- No table: constant extra space.
- Fast in practice: most inputs never retry much.
Fill dp[i][j]: do the first i characters of s match the first j of p?
- Easy to prove: each cell follows one of three rules.
- Adapts: the same table shape handles other pattern rules.
Both run in O(m · n) time in the worst case. The two-pointer version needs no table, so the steps, code and live demo follow it. The DP table comes after the demo.
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.
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.
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.
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.
Code in Python, C++ and Java
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].
Common pitfalls
Reading p[j] after the pattern has run out
if p[j] == "?" or p[j] == s[i]:
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
return j == len(p)
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.
Edge cases
"" and "**"The main loop never runs, the tail loop skips both stars, and the answer is true.
The first character has nothing to match and no star was saved, so the answer is false at once.
Complexity
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.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.