Wildcard Matching (LeetCode 44): Solution and Explanation

Hard
String
Dynamic Programming
Greedy
Recursion

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Let m and n be the lengths of s and p, and create a (m + 1) × (n + 1) table of False.
  2. Set dp[0][0] = True.
  3. For each j, if p[j - 1] is '*', set dp[0][j] = dp[0][j - 1] so leading stars can match the empty string.
  4. For each i from 1 to m and j from 1 to n, if p[j - 1] is '*', set dp[i][j] = dp[i - 1][j] or dp[i][j - 1].
  5. Else if p[j - 1] is '?' or equals s[i - 1], set dp[i][j] = dp[i - 1][j - 1].
  6. Return dp[m][n].

Step-by-step example

s = "abc", p = "a*c"
  1. Row 0: dp[0][0] is True, and the pattern starts with 'a', so dp[0][1], dp[0][2] and dp[0][3] are all False.
  2. Row 1 (string "a"): 'a' matches 'a', so dp[1][1] = dp[0][0] = True. The star gives dp[1][2] = dp[0][2] or dp[1][1] = True. 'c' does not match 'a', so dp[1][3] is False.
  3. Row 2 (string "ab"): dp[2][1] is False, the star gives dp[2][2] = dp[1][2] = True (the star absorbs 'b'), and dp[2][3] is False.
  4. Row 3 (string "abc"): dp[3][2] = dp[2][2] = True, and 'c' matches 'c', so dp[3][3] = dp[2][2] = True.
  5. 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]

Time and space complexity

Time

O(m × n)

Every one of the (m + 1) × (n + 1) cells is filled with constant work.

Space

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] and p[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.