Wildcard Matching (LeetCode 44): Solution and Explanation
You get a string and a pattern where '?' matches exactly one character and '*' matches any sequence of characters, including an empty one. Decide whether the pattern matches the entire string, not just part of it.
Watch it run step by step
Try your own input and write the code →Intuition
A direct recursion compares characters from the front. Ordinary letters and '?' consume one character from each side. The '*' is where it branches: it can match nothing, so you skip it in the pattern, or match one more character, so you consume a string character and keep the '*' for later. Without caching, a pattern with several stars explores an exponential number of branches, because the same pair of positions gets reached in many different ways.
Since the outcome only depends on how much of the string and the pattern are left, cache it. Let dp[i][j] be True when the first i characters of s match the first j characters of p. The empty string matches the empty pattern, so dp[0][0] is True. An empty string can still match a pattern prefix made entirely of stars, which is the leading star loop in the reference code.
For other cells, look at the last pattern character. If it is '*', either it matches nothing, giving dp[i][j - 1], or it absorbs the last string character, giving dp[i - 1][j] (the star stays available to absorb more). If it is '?' or equal to the string character, both sides drop one character and you inherit dp[i - 1][j - 1]. Otherwise the cell stays False.
Filling the table row by row from the top-left means every cell's dependencies are already computed, and the answer sits in dp[m][n].
Approach: Bottom-up DP over prefixes
- Let m and n be the lengths of s and p, and create a
(m + 1) × (n + 1)table of False. - Set
dp[0][0] = True. - For each j, if
p[j - 1]is '*', setdp[0][j] = dp[0][j - 1]so leading stars can match the empty string. - For each i from 1 to m and j from 1 to n, if
p[j - 1]is '*', setdp[i][j] = dp[i - 1][j] or dp[i][j - 1]. - Else if
p[j - 1]is '?' or equalss[i - 1], setdp[i][j] = dp[i - 1][j - 1]. - Return
dp[m][n].
Step-by-step example
s = "abc", p = "a*c"
- Row 0:
dp[0][0]is True, and the pattern starts with 'a', sodp[0][1],dp[0][2]anddp[0][3]are all False. - Row 1 (string "a"): 'a' matches 'a', so
dp[1][1] = dp[0][0] = True. The star givesdp[1][2] = dp[0][2] or dp[1][1] = True. 'c' does not match 'a', sodp[1][3]is False. - Row 2 (string "ab"):
dp[2][1]is False, the star givesdp[2][2] = dp[1][2] = True(the star absorbs 'b'), anddp[2][3]is False. - Row 3 (string "abc"):
dp[3][2] = dp[2][2] = True, and 'c' matches 'c', sodp[3][3] = dp[2][2] = True. - The answer
dp[3][3]is True: 'a' matches a, '*' matches b and 'c' matches c.
Code: Python, Java, C++
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
7 # Handle leading *
8 for j in range(1, n + 1):
9 if p[j - 1] == '*':
10 dp[0][j] = dp[0][j - 1]
11
12 for i in range(1, m + 1):
13 for j in range(1, n + 1):
14 if p[j - 1] == '*':
15 # * matches empty or one+ characters
16 dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
17 elif p[j - 1] == '?' or s[i - 1] == p[j - 1]:
18 dp[i][j] = dp[i - 1][j - 1]
19
20 return dp[m][n]1class Solution {
2 public boolean isMatch(String s, String p) {
3 int m = s.length(), n = p.length();
4 boolean[][] dp = new boolean[m + 1][n + 1];
5 dp[0][0] = true;
6
7 // Handle leading *
8 for (int j = 1; j <= n; j++) {
9 if (p.charAt(j - 1) == '*') {
10 dp[0][j] = dp[0][j - 1];
11 }
12 }
13
14 for (int i = 1; i <= m; i++) {
15 for (int j = 1; j <= n; j++) {
16 if (p.charAt(j - 1) == '*') {
17 dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
18 } else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
19 dp[i][j] = dp[i - 1][j - 1];
20 }
21 }
22 }
23
24 return dp[m][n];
25 }
26}1class Solution {
2public:
3 bool isMatch(string s, string p) {
4 int m = s.size(), n = p.size();
5 vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
6 dp[0][0] = true;
7
8 // Handle leading *
9 for (int j = 1; j <= n; j++) {
10 if (p[j - 1] == '*') {
11 dp[0][j] = dp[0][j - 1];
12 }
13 }
14
15 for (int i = 1; i <= m; i++) {
16 for (int j = 1; j <= n; j++) {
17 if (p[j - 1] == '*') {
18 dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
19 } else if (p[j - 1] == '?' || s[i - 1] == p[j - 1]) {
20 dp[i][j] = dp[i - 1][j - 1];
21 }
22 }
23 }
24
25 return dp[m][n];
26 }
27};Time and space complexity
O(m × n)
Every one of the (m + 1) × (n + 1) cells is filled with constant work.
O(m × n)
The full DP table is stored.
Other approaches
Greedy two pointers with star backtracking (time O(m × n) worst case, space O(1))
Scan both strings, remember the position of the last '*' and the string index it was matched at. On a mismatch, jump back to just after that star and let it absorb one more character. It uses constant space and is linear in practice.
Rolling one-row DP (time O(m × n), space O(n))
Each row depends only on the previous row and itself, so two arrays of length n + 1 are enough.
Common mistakes
- Forgetting the leading star initialization, so a pattern like "*a" fails to match "a" because
dp[0][1]stays False. - Confusing this with regular expression matching, where '*' repeats the preceding character; here it stands alone and matches any sequence.
- Using
dp[i - 1][j - 1]for the star case, which only lets a star match exactly one character. - Off-by-one indexing: the DP uses prefix lengths, so the current characters are
s[i - 1]andp[j - 1].
Frequently asked questions
How does * work in the wildcard DP?
A star either matches nothing, taking the value from the cell to the left, or matches one more character while staying available, taking the value from the cell above. Combining those two choices lets it match any length.
What is the difference between wildcard matching and regular expression matching?
In wildcard matching '*' matches any sequence on its own. In regular expression matching '*' means zero or more copies of the previous character, which leads to a different recurrence.
Can wildcard matching be done in O(1) space?
Yes, with the greedy two-pointer method that remembers the last star and backtracks to it on mismatches. It is harder to prove correct but avoids the table.
What is the time complexity?
O(m × n) for the DP, where m and n are the lengths of the string and the pattern, since each cell is computed once.