All questions

Wildcard Matching

Premium

Wildcard Matching

Wildcard matching decides whether an entire string is described by a pattern built from literal characters plus two wildcards: ? stands for exactly one character, and * stands for any run of characters, including none at all. This is the classic LeetCode 44 problem — the same style of matching a shell uses when you type *.txt. The catch is that * is greedy in theory but ambiguous in practice: a single * could stand for zero characters or twenty, and your matcher has to consider every split. The pattern must cover the whole string, not just a prefix.

Signature

wildcardMatch(s, pattern)   // string, pattern -> boolean

Return true only if pattern matches all of s from start to end.

Examples

wildcardMatch('adceb', '*a*b');   // true  — the two stars cover 'dce' and ''
wildcardMatch('acdcb', 'a*c?b');  // false — no split makes '?b' land on 'cb'
wildcardMatch('anything', '*');   // true  — a single star matches any string

Notes

  • ? matches exactly one character — never zero, never two. 'a?c' matches 'abc' but not 'ac'.
  • * matches any sequence, including empty'*' matches '', 'a', and 'abcdef' alike. Several *s in a row behave like one.
  • The match must be total — the pattern has to consume the entire string. 'a*' matches 'abc', but 'a' does not.
  • Only these two wildcards — every other character, including letters and digits, matches only itself. There are no character classes or escapes.
  • The empty pattern matches only the empty string'' matches '' and nothing else, so a non-empty string needs a non-empty pattern.

FAQ

What are the time and space complexity?
The bottom-up table fills an (m+1) by (n+1) grid once, where m is the string length and n is the pattern length, so it runs in O(m*n) time and O(m*n) space. The space drops to O(n) if you keep only the previous and current rows.
How is this different from LeetCode 10 regular-expression matching?
Here `*` is a standalone wildcard that matches any run of characters on its own. In regex matching, `*` means zero or more of the element immediately before it, so `a*` pairs with the `a` and matches '', 'a', 'aa', and so on. The two problems look similar but the recurrence for `*` is different.
Why does the empty-string row only stay true through a run of stars?
The empty string can only be matched by a pattern that consumes nothing, and the only wildcard that matches an empty sequence is `*`. So dp[0][j] is true exactly when every pattern character up to j is a star; the first literal or `?` in the pattern makes the rest of that row false.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium