Wildcard Matching

Hard

Topics
StringDynamic ProgrammingGreedy

Given an input string s and a pattern p, return true if p matches the entire s. The pattern supports '?' (matches any single character) and '*' (matches any sequence of characters, including the empty sequence).

Example 1

inputaa
patterna
not matched
The pattern has to account for the whole string, not a part of it. ? stands for exactly one character and * for any run, including none at all — which is the case that catches people out. Here the pattern cannot cover it, so false.
Top row is the string; below it the pattern that must account for every character of it.
Input:  s = "aa", p = "a"
Output: false

Example 2

inputaa
patterna
not matched
Input:  s = "aa", p = "*"
Output: true

Example 3

inputcb
pattern?a
not matched
Input:  s = "cb", p = "?a"
Output: false

Constraints

  • 0 <= s.length, p.length <= 16
  • s contains only lowercase letters.
  • p contains lowercase letters, '?' and '*'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two prefixes determine the state: how much of s and how much of the pattern have been consumed. dp[i][j] is whether the first i characters of s match the first j of the pattern.

The non-star cases are forced. A literal or ? consumes exactly one character from each side, so dp[i][j] = dp[i-1][j-1] when they are compatible. A * has two options and the recurrence takes both: dp[i-1][j] means the star absorbs s[i-1] and stays available, and dp[i][j-1] means the star matches nothing and is done.

The first row is the part that is easy to forget. An empty s matches a pattern of stars only, which is why dp[0][j] = dp[0][j-1] propagates along leading stars and stops at the first non-star.

Approach

  1. Set dp[0][0] = true.
  2. Fill the first row: dp[0][j] = dp[0][j-1] when the pattern character is a star.
  3. For each i, j: on a star take dp[i-1][j] or dp[i][j-1]; on ? or a literal match take dp[i-1][j-1]; otherwise false.
  4. Return dp[n][m].

Dry Run

s = "adceb"   p = "*a*b"

       ''   *    a    *    b
  ''   T    T    .    .    .
  a    .    T    T    T    .
  d    .    T    .    T    .
  c    .    T    .    T    .
  e    .    T    .    T    .
  b    .    T    .    T    T

answer true      the first * matches "", then 'a', then * matches "dce", then 'b'

  ""      vs "*"      true    a star can match nothing
  ""      vs ""       true
  "a"     vs ""       false
  "aa"    vs "a"      false
  "acdcb" vs "a*c?b"  false

Complexity

  • Time — O(|s| · |p|): one constant-time cell each.
  • Space — O(|s| · |p|) for the table, reducible to O(|p|) by keeping two rows.
  • There is also a greedy two-pointer solution that runs in O(|s| + |p|) time and O(1) space: walk both strings, and on a star remember its position and the input position so a later mismatch can backtrack to "let the star eat one more character". It is the better answer and markedly easier to get wrong, which is why the table is the one to write first.

Common Pitfalls

  • Forgetting the first-row initialisation, which makes every pattern with a leading star fail against a short input.
  • Writing the star case as dp[i-1][j-1] or dp[i][j-1]. The star must be able to absorb a character and remain available, which is dp[i-1][j].
  • Treating * as matching exactly one character, or as needing at least one. It matches the empty sequence too.
  • Confusing this with regular-expression matching, where * applies to the preceding character. Here it is a standalone wildcard.
  • Returning early on a literal mismatch. A star earlier in the pattern may still rescue it, which is precisely what the table explores.
  • In the greedy variant, failing to reset the pattern pointer to just after the remembered star on a mismatch, or forgetting to advance the remembered input position — which makes it loop forever.

Full Solution — all languages

class Solution:
    def isMatch(self, s, t):
        n, m = len(s), len(t)
        dp = [[False] * (m + 1) for _ in range(n + 1)]
        dp[0][0] = True
        for j in range(1, m + 1):
            if t[j - 1] == '*':
                dp[0][j] = dp[0][j - 1]
        for i in range(1, n + 1):
            for j in range(1, m + 1):
                if t[j - 1] == '*':
                    dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
                elif t[j - 1] == '?' or t[j - 1] == s[i - 1]:
                    dp[i][j] = dp[i - 1][j - 1]
        return dp[n][m]
SensAI
Beta
Tap the mic to stop voice mode