Wildcard Matching — LeetCode 44 Python Solution

HardGreedyRecursionStringDynamic Programming
Problem
#44
Pattern
Greedy
Reading time
2 min

The problem

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).

Example

Input
s = "aa", p = "a"
Output
false
Explanation
"a" does not match the entire string "aa".

Python solution

Python
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        @cache
        def dfs(i: int, j: int) -> bool:
            if i >= len(s):
                return j >= len(p) or (p[j] == "*" and dfs(i, j + 1))
            if j >= len(p):
                return False
            if p[j] == "*":
                return dfs(i + 1, j) or dfs(i + 1, j + 1) or dfs(i, j + 1)
            return (p[j] == "?" or s[i] == p[j]) and dfs(i + 1, j + 1)

        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 44. Wildcard Matching is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 44. Wildcard Matching?
LeetCode 44. Wildcard Matching is rated Hard on LeetCode.
What is the time complexity of LeetCode 44. Wildcard Matching?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 44. Wildcard Matching?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 44. Wildcard Matching cover?
LeetCode 44. Wildcard Matching is tagged Greedy, Recursion, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview