Problem 44

Abstract / Summary

Determine if a text string matches a pattern that may contain wildcard characters asterisk and question mark.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0044.py

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        @cache
        def match(posS, posP):
            if posS == len(s) and posP == len(p):
                return True
            if posP == len(p):
                return False

            # wildcards
            if p[posP] == "?":
                if posS == len(s):
                    return False
                return match(posS + 1, posP + 1)

            if p[posP] == "*":
                for i in range(posS, len(s) + 1):
                    if match(i, posP + 1):
                        return True
                return False

            if posS == len(s):
                return False

            # same letters
            if p[posP] == s[posS]:
                return match(posS + 1, posP + 1)

            return False

        return match(0, 0)
31 lines | 868 bytes | submitted August 31, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 33% (2+ million submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Greedy
  • Recursion
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic wildcard matching problem where the pattern may contain the special characters ? (matching any single character) and * (matching any sequence of characters, including the empty sequence). The solution is expressed as a recursive depth-first search that is memoized using Python’s functools.cache decorator. By caching intermediate results, the algorithm avoids recomputing the same sub-problems, which is essential for handling the exponential number of possibilities introduced by the * wildcard.

Core Logic

The entry point is the isMatch method, which defines an inner function match(posS, posP). This function receives the current indices in the input string s and the pattern p. The recursion proceeds by examining the character at p[posP] and deciding how to advance the indices.

@cache
def match(posS, posP):
    if posS == len(s) and posP == len(p):
        return True
    if posP == len(p):
        return False

The first two conditional blocks handle the termination conditions. When both indices have reached the ends of their respective sequences, a complete match is reported. If the pattern is exhausted while the string still has characters, the match fails.

Handling the ? Wildcard

When the current pattern character is ?, the algorithm checks that there is still a character left in the string to consume. If the string is already at its end, the match fails; otherwise both indices are advanced by one.

if p[posP] == "?":
    if posS == len(s):
        return False
    return match(posS + 1, posP + 1)

Handling the * Wildcard

The * wildcard is the most complex case because it can represent any number of characters, from zero up to the remainder of the string. The implementation iterates over all possible split points, invoking match recursively for each candidate. The loop starts at the current string position and goes through len(s) + 1, thereby including the empty-match scenario.

if p[posP] == "*":
    for i in range(posS, len(s) + 1):
        if match(i, posP + 1):
            return True
    return False

Because match is cached, each distinct pair (i, posP + 1) is evaluated at most once, preventing the exponential blow-up that a naïve recursive solution would suffer.

Literal Character Comparison

If the pattern character is neither ? nor *, the algorithm treats it as a literal. It first ensures that the string has not been exhausted; if it has, the match fails. When both characters are present, a direct equality check determines whether to continue recursion.

if posS == len(s):
    return False

if p[posP] == s[posS]:
    return match(posS + 1, posP + 1)

return False

The final return False covers the case where the current characters differ, leading to an immediate mismatch.

Edge Cases Addressed

The code explicitly checks for several boundary conditions:

  • Both the input string and the pattern being empty results in a successful match.
  • An empty pattern with a non-empty string returns False because there are no pattern characters left to consume the remaining string characters.
  • A ? at the end of the pattern correctly fails when the string is already exhausted, ensuring that ? never matches an empty position.
  • The * loop includes len(s) + 1 as the upper bound, which allows the wildcard to match zero characters (the case where i == posS) as well as the entire remaining suffix of the string.
  • Literal character comparison is guarded by a check that the string index is still within bounds, preventing out-of-range errors.

Performance Optimizations

The most significant optimization is the use of the @cache decorator on the recursive match function. By storing the result of each (posS, posP) pair, the algorithm eliminates redundant work. For example, when processing a *, many different recursive paths may converge on the same subsequent state; caching ensures that the expensive sub-computation is performed only once.

Another subtle optimization is the early exit in the ? and literal branches. As soon as a mismatch is detected, the function returns without exploring further recursion, reducing the number of cache lookups.

The loop for the * wildcard is written to iterate from the current position to the end of the string, but because each recursive call is cached, the overall number of distinct calls remains bounded by the product of the lengths of s and p. This boundedness keeps the runtime practical even for patterns with multiple * characters.

Overall Flow

The isMatch method simply invokes match(0, 0), starting the recursion from the beginning of both the string and the pattern. The combination of explicit base cases, distinct handling for each wildcard type, and memoization yields a clear and efficient solution to the wildcard matching problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a game where two trains are traveling on tracks. One train is carrying a message made of letters, and the other train is a magic pattern that decides what that message is allowed to look like. The goal is to see if the pattern matches the message exactly.

There is a special helper inside the code that keeps track of where each train is standing at any moment. It looks at the current train car and asks if it matches the pattern car.

If the pattern has a question mark, that acts like a magic portal that can step over exactly one letter in the message. If the pattern has a star, that star is very flexible and can stretch to cover any number of letters, or even no letters at all, until it finds a part that matches the rest of the pattern.

When the pattern finds an ordinary letter, it just checks to see if the message has the same letter in that spot. If the letters match, the helper moves both trains forward to check the next spot.

This happens over and over, jumping from car to car, until the trains reach the very end. If both trains finish at the same time and everything lined up perfectly along the way, then the pattern has successfully matched the message. The little memory tool helps out so that if the trains have already visited a certain spot, the computer remembers what happened before and does not have to do the work again.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.11 | σ = 1.29

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, PHP, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
50 links | 34 authors | 11 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality